TS:将联合类型传递给接受子类型的函数
TS: Pass Union Type To Function That Accepts Subtype
// Example Code:
type Type1 = {
a: string;
};
type Type2 = {
a: string;
b: number;
};
type Type3 = {
a: string;
b: string;
c: string;
d: object;
};
type Types = Type1 | Type2 | Type3;
function getType(thing: Types) {
// ...
}
function processByType(thingsToProcess: Types) {
if (getType(thingsToProcess) === "type1") {
processType1(thingsToProcess);
} else if (getType(thingsToProcess) === "type2") {
processType2(thingsToProcess);
} else if (getType(thingsToProcess) === "type3") {
processType3(thingsToProcess);
} else {
throw Error("Unknown type");
}
}
function processType1(t: Type1) {}
function processType2(t: Type2) {}
function processType3(t: Type3) {}
在上面的代码中,ts 不会让我将 Type
的对象传递给除 processType1 之外的任何函数,因为 Type1 具有与其余部分相同的属性。
如何更改我的代码以使此设置正常工作?
而不是 if (getType(thingsToProcess) === "type1") {
,在函数内部执行比较,以便函数可以用作类型保护。
// example implementation
function isType<T extends Types>(thing: Types, a: string): thing is T {
return thing.a === a;
}
function processByType(thingsToProcess: Types) {
if (isType<Type1>(thingsToProcess, "type1")) {
processType1(thingsToProcess);
if (isType<Type2>(thingsToProcess, "type2")) {
processType2(thingsToProcess);
if (isType<Type3>(thingsToProcess, "type3")) {
processType3(thingsToProcess);
} else {
throw Error("Unknown type");
}
}
// Example Code:
type Type1 = {
a: string;
};
type Type2 = {
a: string;
b: number;
};
type Type3 = {
a: string;
b: string;
c: string;
d: object;
};
type Types = Type1 | Type2 | Type3;
function getType(thing: Types) {
// ...
}
function processByType(thingsToProcess: Types) {
if (getType(thingsToProcess) === "type1") {
processType1(thingsToProcess);
} else if (getType(thingsToProcess) === "type2") {
processType2(thingsToProcess);
} else if (getType(thingsToProcess) === "type3") {
processType3(thingsToProcess);
} else {
throw Error("Unknown type");
}
}
function processType1(t: Type1) {}
function processType2(t: Type2) {}
function processType3(t: Type3) {}
在上面的代码中,ts 不会让我将 Type
的对象传递给除 processType1 之外的任何函数,因为 Type1 具有与其余部分相同的属性。
如何更改我的代码以使此设置正常工作?
而不是 if (getType(thingsToProcess) === "type1") {
,在函数内部执行比较,以便函数可以用作类型保护。
// example implementation
function isType<T extends Types>(thing: Types, a: string): thing is T {
return thing.a === a;
}
function processByType(thingsToProcess: Types) {
if (isType<Type1>(thingsToProcess, "type1")) {
processType1(thingsToProcess);
if (isType<Type2>(thingsToProcess, "type2")) {
processType2(thingsToProcess);
if (isType<Type3>(thingsToProcess, "type3")) {
processType3(thingsToProcess);
} else {
throw Error("Unknown type");
}
}