Notes
Notes copied to clipboard
typescript查遗补漏, 持续更新
trafficstars
获取类上的属性的类型
class A{
n: number
}
const num: A['n'] // number
捕获字符串类型
注意, typeof捕获字符串的类型, 是字面量类型, 不是string
// 捕获字符串的类型与值
const foo = 'Hello World';
// 使用一个捕获的类型
let bar: typeof foo;
// bar 仅能被赋值 'Hello World'
bar = 'Hello World'; // ok
bar = 'anything else'; // Error'
捕获键的名称的字面量类型
先用typeof获取对象类型, 然后用keyof后去键值
const colors = {
red: 'red',
blue: 'blue'
};
type Colors = keyof typeof colors;
let color: Colors; // color 的类型是 'red' | 'blue'
指定构造函数中this的类型
interface A{
x:number
}
let a:(this:A)=>number
a =function(){
this.x =123
this.y = 467// 错误, 不存在y
return 123
}
typeof
返回数据类型
const f = (n:number)=>n+1;
type A = typeof f // => (n:number)=>number;
去除数组中第一个元素
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];
泛型也有默认值
type C = 'c';
type B = 'a'
type A<T=B> = T;
let a:A = 'b' // 'a'
想看下 new Promise() 中 then 和 catch 这个两个的传参变量定义