使用此链接中的函数类型示例-https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
我不明白为什么在这种情况下不会发生类型缩小,而且如果不使用以下命令,返回类型就无法工作:
as NameOrId<T>;
在这种情况下,如何才能更好地编写给定的示例?
示例:
interface IdLabel {
id: number;
}
interface NameLabel {
name: string;
}
type NameOrId<T extends number | string> = T extends string ? NameLabel : IdLabel;
const createLabel2 = <T extends number | string>(nameOrId: T): NameOrId<T> => {
if (typeof nameOrId === "string") {
const result = {
// why in this case type nameOrId
// is (parameter) nameOrId: T & string
// instead of symple string ??
name: nameOrId,
}
return result;
}
return {
id: 123,
} as NameOrId<T>;
};