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. jmeter报Address already in use: connect

    jmeter报Address already in use: connect   用windows进行jmeter压测出现java.net.BindException: Address already ...

  2. Redis二进制安全

    为了便于理解,举一个例子: 在很多编辑器中,都会默认/n是换行字符,也就意味着一串字符存进去,涉及/n都会做一个默认的转义处理,这在编辑语言中,C也有这个特性,例如字符串Hello,\0 World! ...

  3. Bitter.Core系列十一:Bitter ORM NETCORE ORM 全网最粗暴简单易用高性能的 NETCore 之 字段变更收集器

    有时候我们业务层需要记录 数据库表更改之前的值和更改之后的值的记录集合--此过程在 Bitter.Core 中有强有力的支持.Bitter.Core 字段收集器提供了方便简单易用的 收集对象在修改之前 ...

  4. 死锁案例 GAP 锁 没有就插入,存在就更新

    https://mp.weixin.qq.com/s/2obpN57D8hyorCMnIu_YAg 死锁案例八 文 | 杨一 on 运维 转 | 来源:公众号yangyidba 一.前言 死锁其实是一 ...

  5. ACCESS数据库偏移注入

    偏移注入主要是针对知道表,但是不知道字段的ACCESS数据库. 比如我们已经知道了表名是 admin 判断字段数: http://192.168.74.136:8002/Production/PROD ...

  6. 设计模式c++(3)——观察者模式

    观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖着都会收到通知并自动更新. 当两个对象之间松耦合,他们依然可以交互,但是不太清楚彼此的细节.观察者模式提供了一种对象设 ...

  7. hadoop知识点总结(二)hdfs分布式文件系统

    1, hdfs设计:减少硬件错误的危害,流式数据访问,大规模数据集,简单的一致性模型 2,特点: 1)移动计算的代价比移动数据的代价低 在异构的软硬件平台间的可移植性 2)局限性 不适合低延迟性数据访 ...

  8. D - D (畅通工程再续)

    相信大家都听说一个"百岛湖"的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现.现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政 ...

  9. hdu 6704 K-th occurrence(后缀数组+可持久化线段树)

    Problem Description You are given a string S consisting of only lowercase english letters and some q ...

  10. 【uva 10954】Add All(算法效率--Huffman编码+优先队列)

    题意:有N个数,每次选2个数合并为1个数,操作的开销就是这个新的数.直到只剩下1个数,问最小总开销. 解法:合并的操作可以转化为二叉树上的操作[建模],每次选两棵根树合并成一棵新树,新树的根权值等于两 ...