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. redis 主从复制 和集群

    redis集群最少三个节点 之间相互通信ping-pong 投票选举机制 主从复制 的话 最少六个节点 ,主三从三

  2. WPF和MVVM的结合使用方法,不可错过

    Model:存储数据模型(类) 也在此业务逻辑,主要负责类文件的存储. ViewModel:连接View和Model,借助Command来负责界面的跳转和调用Model中方法来操作Model的数据. ...

  3. 在Centos7上安装Python+Selenium+Firefox+Geckodriver

    1.事先准备好Centos7的系统 Centos系统是CentOS Linux release 7.4.1708 (Core) 查看Centos内核版本命令cat /etc/centos-releas ...

  4. 快速计算C(n,r)

    在网上见的,引用出处为:http://blog.csdn.net/alexingcool/article/details/7997599 可以在logn内计算出,但是容易溢出. [cpp] view ...

  5. 一:Spring Boot 的配置文件 application.properties

    Spring Boot 的配置文件 application.properties 1.位置问题 2.普通的属性注入 3.类型安全的属性注入 1.位置问题 当我们创建一个 Spring Boot 工程时 ...

  6. mysql修改最大连接数

    root@localhost ~]# nano /etc/my.cnf编辑my.cnf在[mysqld]中加入:set-variable=max_connections=1000 更改 MySQL 在 ...

  7. Linux-服务管理命令chkconfig

    Linux-服务管理命令chkconfig 一  chkconfig简介 chkconfig命令主要用来更新(启动或停止)和查询系统服务的运行级信息.谨记chkconfig不是立即自动禁止或激活一个服 ...

  8. go语言常见面试题

    前言 从网上找了一些面试题,觉得有意思的我都记录下来,自己学习和大家一起学习吧. 有些初级的题目只放答案,一些值得探讨的问题我会写上我自己的分析过程,希望大家多多交流. 原文链接 选择题 1.[初级] ...

  9. 如何为Kafka集群确定合适的分区数以及分区数过多带来的弊端

    通过之前的文章<Kafka分区分配策略>和<Kafka高性能揭秘>,我们了解到:Kafka高吞吐量的原因之一就是通过partition将topic中的消息保存到Kafka集群中 ...

  10. docker 运用

    本文采用centos7,记录docker的简单运用方式 https://www.runoob.com/docker/docker-container-usage.html 1.安装odcker 2.启 ...