英文:
Is there a way to tell TypeScript to use less common type without explicit type declaration?
问题
I'm here to provide the translated code part:
我正在尝试使用类型和泛型,所以我想出了这个:
type TypeMap = {
"string": string,
"number": number
}
type IndexedType<Key extends keyof TypeMap> = TypeMap[Key];
function testFunc<Key extends keyof TypeMap>(key: Key, item: IndexedType<Key>) {
// ...
}
当我将第一个参数传递为文字或基本常量时,item 变量的类型将从映射中正确索引:
const key = "number";
// OK
testFunc("number", 5);
// OK
testFunc(key, 5);
// 将引发类型错误
testFunc("string", 5);
但是,当我在对象类型中使用变量时,它会推断出最常见的类型,因此类型将仅为字符串:
const key = { value: "string" };
// 完全不起作用
testFunc(key.value, 5);
是否有一种方法告诉 TypeScript 在没有显式类型声明的情况下使用不太常见的类型?我正在尝试使用类型作为配置的对象来通过泛型推断函数的输出,因此将相同的内容(作为文字和类型)声明两次将导致代码变得混乱,要求在更改配置时同时更改类型和变量声明。
英文:
I'm trying to work with type and generics, so I came up with this:
type TypeMap = {
"string": string,
"number": number
}
type IndexedType<Key extends keyof TypeMap> = TTypeMap[Key];
function testFunc<Key extends keyof TypeMap>(key: Key, item: IndexedType<Key>) {
// ...
}
When I pass first argument as literal or primitive constant, type of item variable is indexed correctly from the map:
const key = "number";
// OK
testFunc("number", 5);
// OK
testFunc(key, 5);
// Will throw a type error
testFunc("string", 5);
However, when I'm using a variable in object type, it infers the best common type, so the type will be just string.
const key = { value: "string" };
// Will not work at all
testFunc(key.value, 5);
Is there a way to tell TypeScript to use less common type without explicit type declaration? I'm trying to use an object with the type as config to infer the output of the function the same way through generics, so declaring the same thing twice (as a literal and the type) will result in much messier code, and requiring to change both the type and the variable declaration when config is changed.
答案1
得分: 1
以下是翻译好的部分:
const key = { value: "string" } as const;
// 或者:
const key = { value: "string" as const };
(即将整个对象或只将value
的值设为const类型)。
查看文档:
另外,TypeScript 5.0 引入了const
类型修饰符,可以用于函数定义,而不是变量声明,但我不确定除非将整个对象传递给函数,否则在这里是否可行。以下是更多信息以备不时之需:
英文:
This code:
const key = { value: "string" };
// Will not work at all
testFunc(key.value, 5);
should work if you change the key
declaration to:
const key = { value: "string" } as const;
or:
const key = { value: "string" as const };
(i.e. make the whole object or just the value of value
a const type.)
See the documentation:
Also, TypeScript 5.0 introduced the const
type modifier, that can be used on the function definition instead of the variable declarations, but I'm not sure if that could work here unless you passed the entire object to the function. But here is more info just in case you can use it:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论