Notes icon indicating copy to clipboard operation
Notes copied to clipboard

typescript查遗补漏, 持续更新

Open any86 opened this issue 6 years ago • 7 comments
trafficstars

获取类上的属性的类型

class A{
    n: number
}

const num: A['n'] // number

any86 avatar Jun 11 '19 01:06 any86

捕获字符串类型

注意, typeof捕获字符串的类型, 是字面量类型, 不是string

// 捕获字符串的类型与值
const foo = 'Hello World';

// 使用一个捕获的类型
let bar: typeof foo;

// bar 仅能被赋值 'Hello World'
bar = 'Hello World'; // ok
bar = 'anything else'; // Error'

any86 avatar Jun 11 '19 01:06 any86

捕获键的名称的字面量类型

先用typeof获取对象类型, 然后用keyof后去键值

const colors = {
  red: 'red',
  blue: 'blue'
};

type Colors = keyof typeof colors;

let color: Colors; // color 的类型是 'red' | 'blue'

any86 avatar Jun 11 '19 01:06 any86

指定构造函数中this的类型

interface A{
    x:number
}
let a:(this:A)=>number
a =function(){
    this.x =123
    this.y = 467// 错误, 不存在y
    return 123 
}

any86 avatar Jun 11 '19 05:06 any86

typeof

返回数据类型

const f = (n:number)=>n+1;
type A = typeof f // => (n:number)=>number;

any86 avatar Jun 15 '19 04:06 any86

去除数组中第一个元素

type Tail<Tuple extends any[]> = ((...args: Tuple) => void) extends ((a: any, ...args: infer T) => void) ? T : never;
type A = [number, string, null, ()=>void];
type B = Tail<A> // [string, null, ()=>void];


any86 avatar Jun 17 '19 11:06 any86

泛型也有默认值

type C = 'c';
type B = 'a'
type A<T=B> = T;
let a:A = 'b' // 'a'

any86 avatar Jun 20 '19 05:06 any86

想看下 new Promise()thencatch 这个两个的传参变量定义

Travis-hjs avatar Sep 18 '19 02:09 Travis-hjs