我具有预定义的字符串数组STRINGS_ARR
.
我正在try 使用该数组中的字符串创建对象STRINGS_OBJ
.
对象的每个键应该是通过从输入字符串中移除下划线字符来动态生成的,值应该是输入字符串本身.
例如:如果输入的字符串是‘Some_Test_Name’,则key应该是‘SomeTestName`,key的值应该是’Some_Test_Name‘.
我能够编写代码来满足需求,并使用所需的键/值对生成这样的对象.
但是,我不能编写类型/定义对象的 struct ,以便类型脚本能够正确地推断给定键的值.
这就是我到目前为止所拥有的,而TypeScrip无法推断出Value
的类型,这是正确的,因为我试图从InputString
中提取的Key
已经被修改,不再匹配.
type InputStringMap = {
[Key in KeyName<InputString>]: Extract<InputString, Key>
};
type Key = keyof InputStringMap;
type Value = InputStringMap[Key];
// ^? type Value = never
这种对象的正确类型/定义应该是什么?
type InputString = 'Test_String_1' | 'Test_String_2';
const STRINGS_ARR: InputString[] = ['Test_String_1', 'Test_String_2'];
type KeyName<S extends string> = string extends S ? 'Error' : S extends `${infer A}_${infer B}` ? KeyName<`${A}${B}`> : S;
type InputStringMap = {
[Key in KeyName<InputString>]: Extract<InputString, Key>
};
type Key = keyof InputStringMap;
type Value = InputStringMap[Key];
// ^? type Value = never
const keyValuePairs = STRINGS_ARR.map<[Key, Value]>((str) => [str.replace(/_/g, '') as Key, str as Value]);
const STRINGS_OBJ = Object.fromEntries(keyValuePairs) as InputStringMap;