本周typescript实战小技巧(1)

360 阅读1分钟

最近用ts写了一个vue小插件, 收获了些小知识点, 和大家分享下. 未来还会持续更新.

获取类上的属性的类型

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;

我的项目: 命令式调用vue组件.

github.com/any86/vue-c…