typescript里一些有趣的点

Posted liulun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript里一些有趣的点相关的知识,希望对你有一定的参考价值。

联合类型

在原生的JS里,null和undefined经常会导致BUG的产生,
在ts里,你又想用null,又担心出错的时候
你可以考虑用联合类型,当某值可能为 number或null,你可以声明它的类型为number | null

let a : number | null = 2;

类型兼容

实现接口时,只要包含了接口要求的数据结构即可兼容这个接口

interface Person 
    firstName: string;
    lastName: string;

function greeter(person: Person) 
    return "Hello, " + person.firstName + " " + person.lastName;

let user =  firstName: "Jane", lastName: "User" ;
document.body.innerhtml = greeter(user);

面向对象

继承( extends关键字 )
public private  protected  static  readonly get和set  都有,连namespace也有;
抽象类( abstract关键字 )

关于this

let deck: Deck = 
    // NOTE: The function now explicitly specifies that its callee must be of type Deck
    createCardPicker: function(this: Deck) 
        return () => 
           console.log(this)
        
    

指明this的类型必须是Deck

泛型

function identity<T>(arg: T): T 
    return arg;

let output = identity<string>("myString");  // type of output will be ‘string‘
//或者
let output = identity("myString");  // type of output will be ‘string‘

泛型方法、泛型类、泛型约束都有



 

以上是关于typescript里一些有趣的点的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript:从字符串数组定义联合类型

代码寓于生活 有趣的点~

Typescript零碎总结

LayaBox---TypeScript---变量声明

近5万首《全唐诗》里有趣的秘密,大数据用文本挖掘告诉你

为什么Typescript允许实现抽象类?