如何将字符串数组转换为字符串字面量联合类型?

3

能否将这个转换为:

  const readonlyArray: readonly ['a', 'b', 'c'] = ['a', 'b', 'c'] as const;
  type DesiredType = typeof readonlyArray[number];

将其翻译为:

  const array = ['a', 'b', 'c']; // this will come dynamically and sometimes it will be ['a', 'e', 'f']
  const readonlyArray = array as const;
  type DesiredType = typeof readonlyArray[number];

我认为这是不可能的,但你是否有类似的解决方案来完成相同的工作?
以下是实际问题的简化版本:
我有一个React组件,带有两个props - status: 'a' | 'b'renamedPropB?: string,如果将renamedPropBundefined更改为例如'Z',则status的类型应该变为'a' | 'Z'而不是原始的'a' | 'b'
我的想法是将联合类型的字符串字面量放入字符串数组中,这样就可以动态地更改'b''Z',以及添加或删除联合中现有的字符串字面量,使其更易于操作。
1个回答

4

无法在创建后应用 as const,必须在创建数组或对象时进行操作。

如果数组来自外部源,则我认为答案是否定的。您始终可以获取数组元素的类型,但是如果数组被创建为 string[],则元素类型将是 string,而不是字面量值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接