最近用ts寫(xiě)了一個(gè)小插件, 收獲了些小知識(shí)點(diǎn), 和大家分享下.
獲取類上的屬性的類型
class A{
n: number
}
const num: A['n'] // number
捕獲字符串類型
注意, typeof捕獲字符串的類型, 是字面量類型, 不是string
// 捕獲字符串的類型與值
const foo = 'Hello World';
// 使用一個(gè)捕獲的類型
let bar: typeof foo;
// bar 僅能被賦值 'Hello World'
bar = 'Hello World'; // ok
bar = 'anything else'; // Error'
捕獲鍵的名稱的字面量類型
先用typeof獲取對(duì)象類型, 然后用keyof后去鍵值
const colors = {
red: 'red',
blue: 'blue'
};
type Colors = keyof typeof colors;
let color: Colors; // color 的類型是 'red' | 'blue'
指定構(gòu)造函數(shù)中this的類型
interface A{
x:number
}
let a:(this:A)=>number
a =function(){
this.x =123
this.y = 467// 錯(cuò)誤, 不存在y
return 123
}
typeof
返回?cái)?shù)據(jù)類型
const f = (n:number)=>n+1;
type A = typeof f // => (n:number)=>number;
我的項(xiàng)目: 命令式調(diào)用vue組件.