【问题标题】:Is it possible to use typescript mapped types to make a type of non-function properties of an interface?是否可以使用打字稿映射类型来制作接口的一种非功能属性?
【发布时间】:2020-03-26 12:40:13
【问题描述】:

所以我正在查看 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


    【解决方案1】:

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

    谢谢大家!

    【讨论】:

      【解决方案2】:
        { [K in T]: T[K] extends Function ? undefined : T[K] }
      

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

      【讨论】:

      • 这对我来说不太适用;考虑this;
      • 使用 undefined 而不是 never 意味着属性仍然需要是对象的一部分,但它需要是 undefined 的值
      猜你喜欢
      • 2021-05-15
      • 2019-04-03
      • 2021-04-24
      • 2022-12-07
      • 1970-01-01
      • 2021-08-13
      • 2021-04-18
      • 2019-11-19
      • 2020-06-01
      相关资源
      最近更新 更多