在typescript中指定联合类型
我有这样的想法:在typescript中指定联合类型,typescript,Typescript,我有这样的想法: interface ISome { myValue: number | string; // some more members } 我有一个函数,它将接受一个ISome,它的myValue是一个数字,并像这样使用它: function (some: ISome): number { // I accept only ISome with myValue type number return some.myValue + 3; } typescrip
interface ISome {
myValue: number | string;
// some more members
}
我有一个函数,它将接受一个ISome
,它的myValue
是一个数字,并像这样使用它:
function (some: ISome): number { // I accept only ISome with myValue type number
return some.myValue + 3;
}
typescript编译器会像预期的那样抱怨,因为some.myValue
是数字或字符串。
当然,我可以使用联合类型来检查:
function (some: ISome): number { // I could use a guard
if (typeof some.myValue === "number") {
return some.myValue + 3;
}
}
但这不是我想要的,因为我经常需要这样做。您可以使用交叉点类型覆盖联合类型,并在此处指定
myValue
的类型:
function someFunction(some: ISome & {
myValue: number
}): number {
return some.myValue + 3; // No error
}