我有一个根据选项键值返回不同类型的方法。
class Test {
getData(options: { obj: true }): Object;
getData(options: { obj: false }): any[];
getData(): any[];
getData(options = { obj: false }): Object | any[] {
if (options.obj) {
return {};
} else {
return [];
}
}
}
当将 obj
作为 true
传递时,我将返回对象,否则为数组。这很好用。
const instance = new Test();
const result = instance.getData({ obj: true }); // inffered as array
const result2 = instance.getData(); // inffered as object
问题是当我需要使用动态值时它抛出一个错误:
type boolean is not assignable to type false
function getResult(obj: boolean = false ) {
return instance.getData({ obj });
}
问题是什么?
最佳答案
由于 { obj }
的类型在编译时仅被称为 { obj: boolean }
,编译器不知道选择任何重载,您必须显式提供采用 { obj: boolean }
的重载(因为实现签名不算作函数的公共(public)签名),编译器在这种情况下不会做任何魔术:
class Test {
getData(options: { obj: true }): Object;
getData(options: { obj: false }): any[];
getData(options: { obj: boolean }): Object | any[];
getData(): any[];
// This signature is the implementation and is not conidered when resolving the method
getData(options = { obj: false }): Object | any[] {
if (options.obj) {
return {};
} else {
return [];
}
}
}
编辑
您还可以在方法签名中使用条件类型,这样可以减少签名的数量:
class Test {
getData<T extends boolean>(options: { obj: T }): T extends true ? Object : any[];
getData(): any[];
// This signature is the implementation and is not conidered when resolving the method
getData(options = { obj: false }): Object | any[] {
if (options.obj) {
return {};
} else {
return [];
}
}
}
const instance = new Test();
const result = instance.getData({ obj: true }); // inffered as array
const result2 = instance.getData(); // inffered as object
function getResult(obj: boolean = false) {
return instance.getData({ obj }); // inferred as Object|any[]
}
因为 类型 boolean = true | false
和条件类型分布在联合上,
T 扩展为真? Object : any[];
将是 Object|any[]
当 T
是 boolean
时。当 T
为 true
时,返回值为 Object
,当 T
为 false
时, 返回将是 any
所有如预期的那样
关于javascript - Typescript 重载类型 boolean 不可分配给类型 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932591/