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!

Answers:

Answer

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!

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

You can use a mapped conditional type for that.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.