所以我有一个常量对象
const STUDY_TAGS ={
InstanceAvailability: { tag: "00080056", type: "optional", vr: "string" },
ModalitiesinStudy: { tag: "00080061", type: "required", vr: "string" },
ReferringPhysiciansName: { tag: "00080090", type: "required", vr: "string" },
NumberofStudyRelatedSeries: {
tag: "00201206",
type: "required",
vr: "number",
}
};现在我想根据VR值推断每个对象的返回类型,但是如果我看一下typeof STUDY_TAGS,所有的键值对看起来都是这样的:
InstanceAvailability: {
tag: string;
type: string;
vr: string;
};我能以某种方式强制typescript保留字符串文字,而不是将它们泛化为string类型吗?我想用Record,但是当我查看typeof STUDY_TAGS时,我得到的结果是
Record<string, {
tag: string;
type: string;
vr: "string" | "number";
}我真的迷失在这里,不知道如何解决这个问题。难道不能根据一个具有2个字符串值之一的对象来推断返回类型吗?最后,我想创建一个函数,它接受对象并根据VR值知道返回的类型
function doSomething<Type extends "number" | "string">({tag, type, vr} : {tag : string, type : string, vr: Type}) : Type extends "number" ? number : string
{
if(vr === "string") return "test";
return 0;
}发布于 2021-10-25 12:15:39
我相信函数重载和缩小会对你有所帮助。下面是一个简化的例子:
function doSomething(vr: 'string'): string
function doSomething(vr: 'number'): number
function doSomething(vr: string): string | number {
if(vr === 'string) return 'Test!';
return 0;
}然后,当您调用doSomething时,TypeScript的类型系统可以推断返回类型,因为您告诉它只要vr等于'string',函数就会返回一个字符串,而每当vr等于'number'时,函数就会返回一个数字。
const foo = doSomething('string'); // TypeScript knows 'foo' is a string
const bar = doSomething(2); // TypeScript know 'bar' is a number在TypeScript的操场上使用您的特定用例进行Here is a more complete example。
发布于 2021-10-25 12:55:50
我的主要问题是没有从对象中获取类型信息,因为它会将我的字符串常量泛化为一般的类型字符串,尽管我用Object.freeze()定义了我的对象。解决方案是这样定义对象:
const obj = {a: {test: "hi"}} as const;发布于 2021-10-25 13:04:13
你应该能够声明类型'as const‘
const STUDY_TAGS ={
InstanceAvailability: { tag: "00080056", type: "optional" as const, vr: "string" },
ModalitiesinStudy: { tag: "00080061", type: "required" as const, vr: "string" },
ReferringPhysiciansName: { tag: "00080090", type: "required" as const, vr: "string" },
NumberofStudyRelatedSeries: {
tag: "00201206",
type: "required" as const,
vr: "number",
}
};在上面,我刚刚为type属性添加了'as const‘,这样你就可以看到区别了。您可以将这些属性添加到上面的任何属性中,以获得精确值,而不是它们的原语。
https://stackoverflow.com/questions/69707626
复制相似问题