本周typescript实战小技巧(1)

最近用ts写了一个小插件, 收获了些小知识点, 和大家分享下.

获取类上的属性的类型

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组件.

https://github.com/any86/vue-create-root

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容