首页 > 解决方案 > 你能从只读字符串元组中获得字符串文字的联合吗?

问题描述

我想创建一个描述这样结构的接口......

const myObject: MyInterface = {
  keys: ['a', 'b', 'c'], //Arbitrary length and string literals, array is readonly
  props: {
    a: null //OK
    b: null //OK
    c: null //OK
    d: null //Invalid, 'd' is not in keys tuple
  }
}

据我所知,TypeScript 在编译时推断这一点应该没有问题,因为键数组不能更改并且只有字符串文字。这是我目前尝试过的:

interface MyInterface {
  readonly keys: readonly string[];
  readonly props: Record<this['keys'][number],any>;
}

这只设法推断出键必须是字符串,而不是它们必须与给定的文字匹配。有什么办法可以完成我真正想要的吗?

标签: typescript

解决方案


它在这里更容易使用type,而不是interface.

type Result<T extends ReadonlyArray<string>> = {
    keys: T
} & {
        [P in T[number]]: any // you can put here any type
    };

type Test = Result<['a', 'b', 'c']>

const test: Test = {
    keys: ['a', 'b', 'c'],
    a: 1,
    b: 2,
    c: 3,
    d: 3 // error
}

推荐阅读