【发布时间】:2021-12-10 21:55:00
【问题描述】:
所以我有这个常量对象
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;
};
我可以以某种方式强制打字稿保留字符串文字而不是将它们概括为类型字符串吗?
我想用 Record
Record<string, {
tag: string;
type: string;
vr: "string" | "number";
}
我真的迷路了,不知道如何解决这个问题。不应该以某种方式根据具有 2 个字符串值之一的 Object 推断返回类型吗? 最后我想创建一个函数,它接受对象并根据 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;
}
【问题讨论】:
标签: javascript typescript types