Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typescript查遗补漏, 持续更新 #16

Open
any86 opened this issue Jun 11, 2019 · 7 comments
Open

typescript查遗补漏, 持续更新 #16

any86 opened this issue Jun 11, 2019 · 7 comments

Comments

@any86
Copy link
Owner

any86 commented Jun 11, 2019

获取类上的属性的类型

class A{
    n: number
}

const num: A['n'] // number
@any86 any86 changed the title typescript查遗补漏 typescript查遗补漏, 持续更新 Jun 11, 2019
@any86
Copy link
Owner Author

any86 commented Jun 11, 2019

捕获字符串类型

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

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

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

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

@any86
Copy link
Owner Author

any86 commented Jun 11, 2019

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

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

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

type Colors = keyof typeof colors;

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

@any86
Copy link
Owner Author

any86 commented Jun 11, 2019

指定构造函数中this的类型

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

@any86
Copy link
Owner Author

any86 commented Jun 15, 2019

typeof

返回数据类型

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

@any86
Copy link
Owner Author

any86 commented Jun 17, 2019

去除数组中第一个元素

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 any86 changed the title typescript查遗补漏, 持续更新 ⚡ typescript查遗补漏, 持续更新 Jun 17, 2019
@any86 any86 changed the title ⚡ typescript查遗补漏, 持续更新 typescript查遗补漏, 持续更新 Jun 17, 2019
@any86
Copy link
Owner Author

any86 commented Jun 20, 2019

泛型也有默认值

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

@Travis-hjs
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants