所以我在看Typescript的映射类型。是否可以创建一个包装另一种类型的接口,以从原始类型中删除功能?例如:
interface Person{
name: string,
age: number,
speak(): void,
}
type Data<T> = ?
const dataPerson: Data<Person> ={
name: "John",
age: 20
//Speak removed because it is a function
};
谢谢!
{ [K in T]: T[K] extends Function ? undefined : T[K] }
您可以为此使用映射的条件类型。
您可以这样做:
type NotFunc<T> = {
[K in keyof T]: T[K] extends Function ? never : T[K]
};
因此,例如:
interface A {
b: string;
f(): string;
}
type B = NotFunc<A>;
const b:B = {
b: 'a',
f: () => { } // Type '() => void' is not assignable to type 'never'
}
这是来自打字稿文档(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types),并且有效:
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type Data<T> = Pick<T, NonFunctionPropertyNames<T>>;
谢谢大家!