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. C++ Primer Plus读书笔记(三)复合类型

    这节主要是介绍数组.结构体.类等概念,以及new delete内存管理. 1.数组 首先普及一下C++中字符串的概念,只有在结尾有 \0 的才叫字符串, cout 输出字符串也以空字符为标记进行结束输 ...

  2. CF976B

    这是一道考验思维找规律的题,很有可做性. 正文 题意 一个 n * m 的矩阵,从左上角(1 , 1) 开始,先向下走直到最下方,再向右走到最右,再向上走一个,再走到最左......一直走到(1 , ...

  3. how2j 仿天猫j2EE零散笔记

    1. 在servlet中拼接  :"http://localhost:8080/tmall/admin_property_list?cid=83"  这句话中的cid=83时, c ...

  4. 谁再把IDEA的Project比作Eclipse的Workspace,我就跟谁急

    前言 你好,我是A哥(YourBatman). 有一个观点:若一个Java开发者能把IDEA玩得666,则技术一定不会差:但若玩不转IDEA(如不会设置.定制.解决日常问题.快捷键等等),那大概率水平 ...

  5. HTMl5 特点 标签语法 以及标签

    知识点关于HTML5 的特点以及其标签和标签语法.. <!-- [HTMl5 特点] 向下兼容 用户至上 化繁为简 无插件范围 访问通用性 引入语义 引入原生媒体支持--> <!-- ...

  6. HttpURLConnection下载文件流

    package com.loan.modules; import sun.net.www.protocol.file.Handler; import java.io.*; import java.ne ...

  7. 详解MySQL事务原理

    老刘是即将找工作的研究生,自学大数据开发,一路走来,感慨颇深,网上大数据的资料良莠不齐,于是想写一份详细的大数据开发指南.这份指南把大数据的[基础知识][框架分析][源码理解]都用自己的话描述出来,让 ...

  8. xxl-job之实现流程任务编排思路

    背景   某一天一如既往的上班"旅途"中,我的领导在开早会的时候,说我最近没啥事,于是让我研究一下Activiti工作流引擎与Drools规则引擎,当时也不知道后边具体要做什么,管 ...

  9. Codeforces Round #589 (Div. 2) D. Complete Tripartite(模拟)

    题意:给你n个点 和 m条边 问是否可以分成三个集合 使得任意两个集合之间的任意两个点都有边 思路:对于其中一个集合v1 我们考虑其中的点1 假设点u和1无边 那么我们可以得到 u一定和点1在一个集合 ...

  10. 2019牛客暑期多校训练营(第五场)H.subsequence 2(拓扑)

    题意:给你一个字符串的长度n 现在询问了m*(m-1)/2次 每次都可以询问两个字符 然后 会告诉你只留下这两个字符后 字符串的样子 现在问你能不能还原字符串 如果能就输出字符串 否则输出-1 思路: ...