Is it possible to use typescript mapped types to make a type of non-function properties of an interface?

感情迁移 提交于 2020-02-02 11:59:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!