【发布时间】:2020-05-15 02:39:38
【问题描述】:
我有这个基本情况:
type Ids = "foo" | "bar" | "bazz";
interface IFoo {
foo: string;
}
interface IBar {
bar: number;
}
interface IBazz {
bazz: boolean;
}
type Ret<T extends Ids> = T extends "foo" ? IFoo :
T extends "bar" ? IBar :
T extends "bazz" ? IBazz :
never;
function a<T extends Ids>(id: T): Ret<T> {
switch (id) {
case "bar":
return { bar: 1 };
case "foo":
return { foo: "foo" };
case "bazz":
return { bazz: true };
}
}
const bar: IBar = a("bar");
const foo: IFoo = a("foo");
const bazz: IBazz = a("bazz");
如你所见,Typescript 对我的a 函数实现并不满意。我应该改变什么来编译这个函数但仍然在最后三个语句中保持保证?
【问题讨论】:
-
您能解释一下您为什么要这样做
T extends "foo",我看不出这背后有什么实际原因。我觉得应该是T === "foo" -
@Nicolas 这是 TypeScript 中条件类型的语法。
标签: typescript types conditional-statements union