TypeScript & as & Type Assertion

Type Assertion (as)

That is not vanilla JavaScript, it is TypeScript. As any means consider the typed object as a plain untyped javascript object.

The as keyword is a Type Assertion in TypeScript which tells the compiler to consider the object as another type than the type the compiler infers the object to be.

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-09-11
* @modified
*
* @description TypeScript Type Assertion
* @augments
* @example
* @link
*
*/ const log = console.log; /* <input type="text" data-uid="html-input-type-assertion"> */ const dom = document.querySelector(`[data-uid="html-input-type-assertion"]`); const inputDOM1: HTMLInputElement = dom as HTMLInputElement;
// const inputDOM1: HTMLInputElement = document.querySelector(`[data-uid="html-input-type-assertion"]`) as HTMLInputElement; inputDOM1.value; const inputDOM2: HTMLInputElement = <HTMLInputElement>dom;
// const inputDOM2: HTMLInputElement = <HTMLInputElement>document.querySelector(`[data-uid="html-input-type-assertion"]`); inputDOM2.value; const input = document.querySelector(`[data-uid="html-input-type-assertion"]`); input.value; /* const input: Element | null
Object is possibly 'null'.ts(2531) */ input?.value; /* any
Property 'value' does not exist on type 'Element'.ts(2339)
*/ input?.nodeValue;
// (property) Node.nodeValue: string | null | undefined

as

// TypeScript

function validateToken(token: string) {
return token;
} const token = 'kjadj' as string | undefined; validateToken(token);

Type Assertion

https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions

as-syntax

let someValue: unknown = "this is a string";

let strLength: number = (someValue as string).length;

“angle-bracket” syntax:

let someValue: unknown = "this is a string";

let strLength: number = (<string>someValue).length;

demos

https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

https://basarat.gitbook.io/typescript/type-system/type-assertion


var foo = {};
foo.bar = 123; // Error: property 'bar' does not exist on `{}`
foo.bas = 'hello'; // Error: property 'bas' does not exist on `{}`
interface Foo {
bar: number;
bas: string;
}
var foo = {} as Foo;
foo.bar = 123;
foo.bas = 'hello';

Advanced Types

Type Guards and Differentiating Types

https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types


let pet = getSmallPet();
let fishPet = pet as Fish;
let birdPet = pet as Bird; if (fishPet.swim) {
fishPet.swim();
} else if (birdPet.fly) {
birdPet.fly();
}

refs

https://linguinecode.com/post/how-to-solve-typescript-possibly-undefined-value

https://stackoverflow.com/questions/55781559/what-does-the-as-keyword-do



xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


TypeScript & as & Type Assertion的更多相关文章

  1. [TypeScript] Work with DOM Elements in TypeScript using Type Assertions

    The DOM can be a bit tricky when it comes to typing. You never really know exactly what you're going ...

  2. [golang] go的typeswitch guard(类型区别)语法和type assertion(类型断言)语法

    最近在实现golang,看到个go的特性语法: typeswitch guard. typeswitch guard语法如下: package main import "fmt" ...

  3. 7.2 Go type assertion

    7.2 Go type assertion 类型断言是使用在接口值上的操作. 语法x.(T)被称为类型断言,x代表接口的类型,T代表一个类型检查. 类型断言检查它操作对象的动态类型是否和断言类型匹配. ...

  4. [TypeScript] Use the TypeScript "unknown" type to avoid runtime errors

    The "any" type can be very useful, especially when adding types to an existing JavaScript ...

  5. [TypeScript] Increase TypeScript's type safety with noImplicitAny

    TypeScript tries to infer as much about your code as it can. But sometimes there really is not enoug ...

  6. [TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers

    Using the optional “+” sign together with mapped type modifiers, we can create more explicit and rea ...

  7. Go 的类型断言type assertion

    Go语言中的类型断言,语法上是这样的: x.(T) 其中,x是interface接口的表达式,T是类型,称为被断言类型. 补充一下,接口有接口值的概念,其包括动态类型和动态值两部分. 类型断言根据T的 ...

  8. Go语言中cannot convert adminname (type interface {}) to type *: need type assertion的解决办法

    解决的办法是把string(adminname)替换为adminname.(string).其它类型也是类似.

  9. go 报 need type assertion

    responese_total := m["responses"].([]interface{})[0].(map[string]interface{})["hits&q ...

随机推荐

  1. 使用amoeba实现mysql读写分离

    使用amoeba实现mysql读写分离 1.什么是amoeba? ​ Amoeba(变形虫)项目,专注 分布式数据库 proxy 开发.座落与Client.DB Server(s)之间.对客户端透明. ...

  2. git的使用学习笔记--项目版本操作

    一.使用场景 版本回退:上线失败--需要回退到上个版本 二.操作 先编辑  vim text.txt git status git add .       这个命令能看到所有的增加操作 git com ...

  3. 蓝 / 绿部署(Blue/Green) 金丝雀发布(Canary Release) 功能标记(Feature Flagging)

    https://www.cnblogs.com/apanly/p/8784096.html 最终,我选择了 GraphQL 作为企业 API 网关 蓝 / 绿部署(Blue/Green) 金丝雀发布( ...

  4. 僵尸网络(botnet)概念浅析

    僵尸程序 僵尸程序是用于构建僵尸网络以形成大规模攻击平台的恶意代码.僵尸网络是被黑客集中控制的计算机群,其核心特点是黑客能够通过一对多的命令与控制信道操纵感染僵尸程序的主机执行相同的恶意行为,如可同时 ...

  5. bzoj 2038(莫队算法)

    2038: [2009国家集训队]小Z的袜子(hose) 时间限制: 20 Sec  内存限制: 259 MB 题目描述 作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来 ...

  6. LOJ10144宠物收养所

    HNOI 2004 最近,阿 Q 开了一间宠物收养所.收养所提供两种服务:收养被主人遗弃的宠物和让新的主人领养这些宠物. 每个领养者都希望领养到自己满意的宠物,阿 Q 根据领养者的要求通过他自己发明的 ...

  7. (七)整合 Redis集群 ,实现消息队列场景

    整合 Redis集群 ,实现消息队列场景 1.Redis集群简介 1.1 RedisCluster概念 2.SpringBoot整合Redis集群 2.1 核心依赖 2.2 核心配置 2.3 参数渲染 ...

  8. 《aspose》 word表格循环导出图片

    废话不多说,直接上代码,网上代码都不能用,迫不得已,最后查询了官网的源码.上菜! 模板文件可以自己去github去下载. package com.aspose.words.examples.mail_ ...

  9. Java方式导出EXCEL表格

    最近几天做公司项目,应客户需求需要将表单的数据下载本地存成.xls文件.之前做毕设的时候,就有类似这方面的功能需 求,但是当时也没有做就搁浅了下来,这次补上. 一.业务开发描述 二.前台jsp页面及j ...

  10. Linux提权常用漏洞速查表

    漏洞列表 #CVE #Description #Kernels CVE–2018–18955 [map_write() in kernel/user_namespace.c allows privil ...