打字稿条件参数联合类型

Typescript conditional parameter union types

我正在尝试创建一个接受固定数量的类型化参数的函数,但是根据第一个参数的不同,顺序参数类型会有所不同。

到目前为止,我还没有在 Typescript 文档中找到任何相关内容。

示例:

function myFunc(name: 'one' | 'two', data?: 1 | 2) {
  //
}

// Okay
myFunc('one', 1)
myFunc('two', 2)
myFunc('two')

// Should throw an error
myFunc('one', 2)
myFunc('two', 'string')

您可能想要 overload 函数签名:

function myFunc(name: 'one', data?: 1);
function myFunc(name: 'two', data?: 2);
function myFunc(name: 'one' | 'two', data?: 1 | 2) {
  //
}

// Okay
myFunc('one', 1)
myFunc('two', 2)
myFunc('two')

// Does throw an error
myFunc('one', 2)
myFunc('two', 'string')

可能还有一种方法可以使用 generic function, but overloads are the most straightforward way to do what you're after. I really recommend reading the useful and accessible TypeScript handbook 来深入了解此类内容。

希望对您有所帮助;祝你好运!

正如 jcalz 在 you can in fact achieve this by using generics and the new conditional types 将与 TypeScript 2.8 一起发布的功能中提到的那样。

如果您使用的是基于 npm 的项目,您可以通过像这样安装最新的每晚构建来在本地试用它(如果您只想在本地项目中安装它,则可以省略 -g) :

npm install -g typescript@next

代码如下所示:

// the parens around the conditional expression are optional
function myFunc<T1 extends 'one' | 'two', T2 extends (T1 extends 'one' ? 1 : 2)>(name: T1, data?: T2) {
  // do what you want
}

// No errors
myFunc('one', 1);
myFunc('two', 2);
myFunc('two');

// All of these cause a compile error
myFunc('one', 2);
myFunc('two', 1);
myFunc('three');
myFunc('two', 'string')
myFunc('one', 3);

// the first invocation (i.e. myFunc('one', 1)) leads to this resolved type
function myFunc<"one", 1>(name: "one", data?: 1 | undefined): void