是否可以使用打字稿映射的类型来创建接口的非功能属性?

问题描述 投票:2回答:3

所以我在看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
};

谢谢!

javascript typescript interface mapped-types
3个回答
1
投票
  { [K in T]: T[K] extends Function ? undefined : T[K] }

您可以为此使用映射的条件类型。


0
投票

您可以这样做:

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'
}

0
投票

这是来自打字稿文档(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>>;

谢谢大家!

© www.soinside.com 2019 - 2024. All rights reserved.