能否将这个转换为:
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
,如果将renamedPropB
从undefined
更改为例如'Z'
,则status
的类型应该变为'a' | 'Z'
而不是原始的'a' | 'b'
。我的想法是将联合类型的字符串字面量放入字符串数组中,这样就可以动态地更改
'b'
为'Z'
,以及添加或删除联合中现有的字符串字面量,使其更易于操作。