打字稿,用对象参数重载函数

时间:2021-05-03 10:08:44

标签: typescript

我有一个函数,它接受一个参数对象并返回一个对象。返回的对象将包含一个“bar”键,具体取决于“includeBar”键是否作为选项提供。我尝试了以下重载

interface Options {
    includeBar: boolean
}

interface Return {
    foo: string;
    bar: string;
}

function someFunc(opt: Options & { includeBar: true }): Return;
function someFunc(opt: Options & { includeBar: false }): Omit<Return, "bar">;
function someFunc(opt: any): any {
    // ...
}

const { bar: bar1 } = someFunc({ includeBar: true }); // OK bar1 exists
const { bar: bar2 } = someFunc({ includeBar: false }); // OK bar2 does not exists

在我将声明的对象传递给 myFunc 之前它工作正常:

const options: Options = {
    includeBar: true
}

const { bar } = someFunc(options); // TS Error Types of property 'includeBar' are incompatible. Type 'boolean' is not assignable to type 'false'.

这是一个示例 TS playground

我看到了 this similar question,但是一旦函数被赋予一个声明的对象,答案就会出现同样的问题。

1 个答案:

答案 0 :(得分:1)

您需要对选项声明进行以下更改...

const options = {
    includeBar: true
} as const;

然后打字稿可以告诉

  1. options 的类型比 Options 的类型更窄
  2. 选项不会有它的 自声明以来,值在运行时发生了变化。