Mik*_*aas 2 typescript conditional-types typescript2.8
这个问题类似,但与Typescript 2.8 有点不同:Remove properties in one type from another
我想创建一个函数,它接受一个类型,并返回一个新类型,该类型不包含 Array 类型的属性或其他复杂(嵌套)对象。
我假设条件类型是处理这个问题的最佳(唯一?)方法?如何才能做到这一点?
您可以使用条件类型(以挑选键)创建仅保留原始类型(不包括数组和其他对象)的条件类型,并且Pick
type PrimitiveKeys<T> = {
[P in keyof T]: Exclude<T[P], undefined> extends object ? never : P
}[keyof T];
type OnlyPrimitives<T> = Pick<T, PrimitiveKeys<T>>
interface Foo {
n: number;
s: string;
arr: number[];
complex: {
n: number;
s: string;
}
}
let d : OnlyPrimitives<Foo> // will be { n: number, s: string }
Run Code Online (Sandbox Code Playgroud)
实际的函数实现应该非常简单,只需迭代对象属性并排除object
function onlyPrimitives<T>(obj: T) : OnlyPrimitives<T>{
let result: any = {};
for (let prop in obj) {
if (typeof obj[prop] !== 'object' && typeof obj[prop] !== 'function') {
result[prop] = obj[prop]
}
}
return result;
}
let foo = onlyPrimitives({ n: 10, s: "", arr: [] }) ;
Run Code Online (Sandbox Code Playgroud)
编辑添加了对可选字段的正确处理。
| 归档时间: |
|
| 查看次数: |
6031 次 |
| 最近记录: |