最近用ts写了一个vue小插件, 收获了些小知识点, 和你们分享下. 将来还会持续更新.vue
class A{
n: number
}
const num: A['n'] // number
复制代码
注意, typeof捕获字符串的类型, 是字面量类型, 不是stringgit
// 捕获字符串的类型与值
const foo = 'Hello World';
// 使用一个捕获的类型
let bar: typeof foo;
// bar 仅能被赋值 'Hello World'
bar = 'Hello World'; // ok
bar = 'anything else'; // Error'
复制代码
先用typeof获取对象类型, 而后用keyof后去键值github
const colors = {
red: 'red',
blue: 'blue'
};
type Colors = keyof typeof colors;
let color: Colors; // color 的类型是 'red' | 'blue'
复制代码
interface A{
x:number
}
let a:(this:A)=>number
a =function(){
this.x =123
this.y = 467// 错误, 不存在y
return 123
}
复制代码
返回数据类型typescript
const f = (n:number)=>n+1;
type A = typeof f // => (n:number)=>number;
复制代码