TypeScript常用技巧
根据value获得key的类型
type S = {
a: 1
b: '2'
}
type Get<S, V> = { [k in keyof S]: S[k] extends V ? k : never }[keyof S]
type a = Get<S, 1>
对key限制为obj的属性名称
interface X {
a: number
b: string
c: number
}
function getProperty<T extends X, K extends keyof T>(obj: T, key: K) {
return obj[key]
}
function getProperty(obj: X, key: keyof X) {
return obj[key]
}
如何限制this的类型
getName(this: Obj) {}
Object.keys返回的类型不对
const a = {
b: 1,
c: '2'
}
const keys = Object.keys(a) as Array<keyof typeof a>
根据一个对象,得到对象所有value
const obj = {
a: 1,
b: 2,
c: 3
}
type Obj = 1 | 2 | 3
const obj = {
a: 1,
b: 2,
c: 3
} as const
type Obj = typeof obj[keyof typeof obj]
根据一个对象,得到对象所有value,不在同一层级
const a = {
a: 1,
b: 2,
c: 3,
x: {
d: 4
}
} as const
type Value = 1 | 2 | 3 | 4
const a = {
a: 1,
b: 2,
c: 3,
x: {
d: 4
}
} as const
type ObjVal<T> = {
[K in keyof T]: T[K] extends object ? ObjVal<T[K]> : T[K]
}[keyof T]
type x = ObjVal<typeof a>
interface内部的key和value
interface A {
a: {
name: string;
age: number;
};
b: {
w: boolean;
h: symbol;
};
}
type GetKeys<U> = U extends Record<infer K, any> ? K : never;
type UnionToIntersection<U> = {
[K in GetKeys<U>]: U extends Record<K, infer T> ? T : never;
};
type Z = UnionToIntersection<A[keyof A]>;