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. https://www.cnblogs.com/AloneSword/p/3209653.html

    proc/sys/net/ipv4/下各项的意义 - 孤剑 - 博客园 https://www.cnblogs.com/AloneSword/p/3209653.html

  2. udp聊天器

    import socket def send_msg(udp_socket): """获取键盘数据,并将其发送给对方""" # 1. 从键盘 ...

  3. ThinkPHP 5.0.15中的update注入漏洞

    漏洞demo: public function inc() { $username = request()->get('name/a'); db('user')->insert(['nam ...

  4. SpringMVC听课笔记(七:Restful CRUD)

    这章貌似没有什么可讲的,可以看GitHub工程代码: https://github.com/heyboom/SpringMVC_Rest_CRUD

  5. 十三:SpringBoot-基于Yml配置方式,实现文件上传逻辑

    SpringBoot-基于Yml配置方式,实现文件上传逻辑 1.文件上传 2.搭建文件上传界面 2.1 引入页面模板Jar包 2.2 编写简单的上传页面 2.3 配置页面入口 3.SpringBoot ...

  6. CSS中一些重要概念

    在CSS的最后一个博客中,将学习整理一些CSS中的重要概念,对这些重要概念的掌握,将对CSS的认识十分重要. 了解这些概念对深入理解CSS的本质十分重要:(1)包含块containing block ...

  7. MySql(二)索引的设计与使用

    MySql(二)索引的设计与使用 一.索引概述 二.设计索引的原则 三.BTREE索引与HASH索引 一.索引概述 所有Mysql列类型都可以被索引,对相关列使用索引时提高select操作性能的最佳途 ...

  8. (9)Linux的哲学思想及文件概念

    一.Linux的哲学思想 1. 一切皆文件 把几乎所有资源统统抽象为文件形式,包括硬件设备,甚至通信接口等,便于统一管理和定义: 对文件的操作有:open,read,write,close,delet ...

  9. flutter--Dart基础语法(三)类和对象、泛型、库

    一.前言 Flutter 是 Google 开源的 UI 工具包,帮助开发者通过一套代码库高效构建多平台精美应用,Flutter 开源.免费,拥有宽松的开源协议,支持移动.Web.桌面和嵌入式平台. ...

  10. 配置七牛云图床 + Typora

    配置七牛云图床工具 使用图床+Typora可以方便快捷的撰写图文博客 我这里以七牛云进行示例,讲解如何去配置 七牛云是属于收费图床,目前还在测试,不过对于使用量不大的我来说应该免费是足够了的,不过需要 ...