ts 关键字 keyof 和 typeof、in
1. typeof 提取类型
- 提取对象的类型
const person = {
name:'Rock',
age:22,
}
type perSonType = typeof person
// 等价于
type personType = {name: string, age: number}
- 提取数组的类型
const arr = ['rock',22,true]
type arrType = typeof arr
// 等价于 type arrType = (atring | number | boolean)[]
let arr1:arrType = ['123','234',4234,false]
- typeof 提取函数类型
const func = (a:number)=>{
if(a===1) return false
else return 666
}
type funcType = typeof func;
// 等价于 type funcType = (a: number) => (false | 666)
// 下面会报错,123 不等于666
const func1:funcType = (b)=>{
return 123
}
2. keyof 获取 "键" 的联合类型
- keyof 后面可以跟class 定义的对象
class Person{
name:123
age:18
constructor(name,age) {
this.name = name
this.age = age
}
hello(){
`${this.name},say hello`
}
}
// 相当于 type k1 = "name" | "age" | "hello" ,提取到的对象没有继承的属性
type k1 = keyof Person
- 跟一个数组[]
// 相当于type k = never
type k2 = {}
// 可以提取到数组的继承属性
// 相当于 type k3 = "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | ...
type k3 = keyof []
- 跟字符串 ""
// 试试字符串
// 相当于 type k4 = "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | ...
type k4 = keyof ''
- 跟类型
// keyof
type PersonType = {
name:string,
age:number
}
// 等价于 type keyofPerson = "name" | "age"
type keyofPerson = keyof PersonType
注意:
keyof 后面不能直接跟 {} (字面量) 定义的非空对象,空对象的返回值是never
const obj = {
name:'Rock,
age:18
}
type k = keyof obj // 报错
// never
type k1 = keyof {}
3. in 关键字
in的右侧一般会跟一个联合类型,使用in操作符可以对该联合类型进行迭代。 其作用类似JS中的for...in或者for...of
type roles = 'admin'| 'user' | 'student' | 'teacher'
type roleAgeType = {
[a in roles]: number
}
// 相当于
type roleType1 = {
admin:string
user:string
student:string
teacher:string
}
4. typeof 和 keyof 连用
typeof 提取类型,keyof提取类型的的键组合为联合类型。
const person = {
name:'Rock',
age:19,
gender: false,
action:()=>{
console.log('hello');
}
}
// 相当于 type propertyType = "gender" | "name" | "action" | "age"
type propertyType = keyof typeof person
5. typeof、keyof 、in 连用
const obj = {
name:'Rock',
age: 20
}
//等价于
type myType = {
name:string
age:string
}
type myType = {
[key in keyof typeof obj]: string
}