【问题标题】:TYPESCRIPT - How to allow for more types in every property of a TypeScript object?TYPESCRIPT - 如何在 TypeScript 对象的每个属性中允许更多类型?
【发布时间】:2020-08-10 20:34:56
【问题描述】:

我的项目中有一个对象。这是架构:

IObject : {
  prop1: number;
  prop2: number;
}

对于 90% 的使用情况,这是我想要的类型。但有一些情况要求我还为每个属性返回一个字符串。因此,对于某些情况,我想要一个返回的接口:

object: IObjectWithStrings // Here I want to add string to each property as acceptable type.

// Something like
object: IObjects extends string

我该怎么做?我可以为此创建一个新接口,但我宁愿拥有原始接口并对其进行扩展。谢谢!!

【问题讨论】:

    标签: typescript object interface


    【解决方案1】:

    您可以使用泛型来做到这一点。在这个例子中,你可以定义一个基本类型IObject<T>,其中T代表动态类型,像这样:

    type IObject<T> = {
      prop1: T;
      prop2: T;
    }
    

    您可以直接使用IObject&lt;number&gt;IObject&lt;number | string&gt;,其中number | string 表示“允许prop1 为两者之一”(联合类型),或者您可以使用基本类型IObject&lt;T&gt; 定义其他类型:

    type IObjectNumber = IObject<number>;
    type IObjectWithString = IObject<number | string>;
    
    const objNum: IObjectNumber = { prop1: 10, prop2: 'abc' } // this will throw error
    const objNumStr: IObjectWithString = { prop1: 10, prop2: 'abc' } // this will not throw error
    

    【讨论】:

    • 谢谢。我想到了那个。问题是,object 来自 DTO,不应更改以接受不同的值,只是导致 FE 需要接受带有字符串的默认值。它也不应该是通用的。不过谢谢..我会投票,但我不能接受是正确的。
    【解决方案2】:

    您可以从现有的类型中创建另一种类型:

    type IObject = {
        prop1: number;
        prop2: number;
    }
    
    type IObjectString = {
        [K in keyof IObject]: string 
    }
    
    type IObjectStringOrOriginal = {
        [K in keyof IObject]: string | IObject[K]
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2022-11-02
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      相关资源
      最近更新 更多