问题
so I was looking at Typescript's mapped types. Would it be possible to create an interface that wraps another type that removes functions from the original type? For example:
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
};
Thanks!
回答1:
This is from the typescript documentation (https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types) and works:
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type Data<T> = Pick<T, NonFunctionPropertyNames<T>>;
Thanks everyone!
回答2:
{ [K in T]: T[K] extends Function ? undefined : T[K] }
You can use a mapped conditional type for that.
来源:https://stackoverflow.com/questions/59129805/is-it-possible-to-use-typescript-mapped-types-to-make-a-type-of-non-function-pro