简体   繁体   中英

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

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!

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!

  { [K in T]: T[K] extends Function ? undefined : T[K] }

You can use a mapped conditional type for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM