[TypeScript] type、typeof、keyof
2021-06-01 本文已影响0人
捡了幸福的猪
typescript 一点一点的知道~
1、type
type用于定义类型,常用于定义类型别名(类型别名就是用来给一个类型起个新名字, 类型别名常用于联合类型。
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 核心的区别在于 type 一旦定义就不能再添加新的属性,而 interface 总是可扩展的。
- 扩展interface
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey
- 扩展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 操作符用来获取一个变量或对象的类型; 巧了JavaScript中也有typeof , 先来复习下在JavaScript中的用法
在JavaScript 中 typeof 操作符返回一个字符串,表示未经计算的操作数的类型

TypeScript 中的typeof:
const layout = {
labelCol: { span: 6 },
wrapperCol: { span: 16 },
}
type layoutType = typeof layout
查看 layoutType 的值:

typeof也可以获取函数的类型:
function toArray(x: number): Array<number> {
return [x];
}
type layoutType = typeof toArray
查看layoutType的值:

3、keyof
keyof 操作符可以用于获取某种类型的所有键,其返回类型是联合类型
与typeof 联合使用:
const layout = {
labelCol: { span: 6 },
wrapperCol: { span: 16 },
}
type layoutType = typeof layout
const test: keyof layoutType = {};
查看test的类型:

转载可以,先点赞哈~