typescript 一點(diǎn)一點(diǎn)的知道~
1举哟、type
type用于定義類型,常用于定義類型別名(類型別名就是用來(lái)給一個(gè)類型起個(gè)新名字迅矛, 類型別名常用于聯(lián)合類型妨猩。
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
} else {
return n();
}
}
幾乎 interface 的所有特性 type都有, type與interface 核心的區(qū)別在于 type 一旦定義就不能再添加新的屬性秽褒,而 interface 總是可擴(kuò)展的壶硅。
- 擴(kuò)展interface
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey
- 擴(kuò)展type
type Animal = {
name: string
}
type Bear = Animal & {
honey: Boolean
}
const bear = getBear();
bear.name;
bear.honey;
- interface 增加屬性
interface Window {
title: string
}
interface Window {
ts: import("typescript")
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
- type 增加屬性
type Window = {
title: string
}
type Window = {
ts: import("typescript")
}
// Error: Duplicate identifier 'Window'.
2、typeof
在 TypeScript 中销斟,typeof 操作符用來(lái)獲取一個(gè)變量或?qū)ο蟮念愋停?巧了JavaScript中也有typeof , 先來(lái)復(fù)習(xí)下在JavaScript中的用法
在JavaScript 中 typeof 操作符返回一個(gè)字符串庐椒,表示未經(jīng)計(jì)算的操作數(shù)的類型
js typeof 的值 from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof
TypeScript 中的typeof:
const layout = {
labelCol: { span: 6 },
wrapperCol: { span: 16 },
}
type layoutType = typeof layout
查看 layoutType 的值:layoutType 的值.png
typeof也可以獲取函數(shù)的類型:
function toArray(x: number): Array<number> {
return [x];
}
type layoutType = typeof toArray
查看layoutType的值:layoutType 的值.png
3、keyof
keyof 操作符可以用于獲取某種類型的所有鍵蚂踊,其返回類型是聯(lián)合類型
與typeof 聯(lián)合使用:
const layout = {
labelCol: { span: 6 },
wrapperCol: { span: 16 },
}
type layoutType = typeof layout
const test: keyof layoutType = {};
查看test的類型: test的類型.png
轉(zhuǎn)載可以约谈,先點(diǎn)贊哈~