javascript - Typescript 重载类型 boolean 不可分配给类型 false

标签 javascript typescript

我有一个根据选项键值返回不同类型的方法。

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[]Tboolean 时。当 Ttrue 时,返回值为 Object,当 Tfalse 时, 返回将是 any 所有如预期的那样

关于javascript - Typescript 重载类型 boolean 不可分配给类型 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932591/

相关文章:

使用 instanceof 时,Typescript 不会缩小变量

javascript - 我可以获得 Canvas 上下文的当前旋转 Angular 吗?

javascript - 如何动态加载基础轨道?

javascript - 无法在 Angular 指令的 Karma 测试中加载模板 HTML 文件

javascript - typescript :请求类型上不存在属性 'decoded'

angular - 如何从 Observable 返回数组

javascript - 使用模块编译 Typescript 以在浏览器中运行

javascript - 重复的 JavaScript 名称。拥有它们不好吗?

javascript - 使用 Meteor 对集合中的对象进行分组

javascript - 在 javascript/typescript 中绘制形状并填充颜色