【问题标题】:How to ensure an atrribute is a subarray of another attribute in typescript?如何确保一个属性是打字稿中另一个属性的子数组?
【发布时间】:2020-11-03 14:16:05
【问题描述】:

我想创建一个接口,其中一个数组属性的值只能是另一个数组属性的值的子集。所以它会像这样工作:

interface Arrays {
    array: string[],
    subArray: ... // some type, string[] is not enough
}

const arrayOne: Arrays = {
    array: ['a', 'b', 'c'],
    subArray: ['a', 'b'], // ok, both 'a' and 'b' are in array
};

const arrayTwo: Arrays = {
    array: ['a', 'b', 'c'],
    subArray: ['a', 'd'], // incorrect type, 'd' is not in array
};

我可以在运行时验证它,但是有没有办法在 typescript 中做到这一点?

【问题讨论】:

    标签: arrays typescript sub-array


    【解决方案1】:

    一种方法是提取允许的值,例如

    type AllowedChars = ["a", "b", "c"]
    
    interface Arrays<T> {
      array: T,
      subArray: Partial<T>
    }
    
    const arrayOne: Arrays<AllowedChars> = {
      array: ['a', 'b', 'c'],
      subArray: ['a', 'b'], // ok, both 'a' and 'b' are in array
    };
    
    const arrayTwo: Arrays<AllowedChars> = {
      array: ['a', 'b', 'c'],
      subArray: ['a', 'd'], // incorrect type, 'd' is not in array
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      相关资源
      最近更新 更多