如何扩展或重用函数类型脱句?

时间:2018-09-05 10:11:11

标签: typescript typescript2.0

因此,到目前为止,我有一个函数会根据输入返回不同的值

type func = (
  a: string, b:string, c:string, d:string, e:string, f:string, list?: boolean
) => string | string[]

const myFunction: func = require('./foo')

但是,这并不完全正确,基本上,如果通过list = true,则返回的是array,否则返回string

所以我重写了类型

type func1 = (
  a: string, b:string, c:string, d:string, e:string, f:string
) => string

type func2 = (
  a: string, b:string, c:string, d:string, e:string, f:string, list: true
) => string[]

const myFunction: func1 & func2 = require('./foo')
const aa = myFunction('a','b','c','d','e','f') // string
const bb = myFunction('a','b','c','d','e','f', true) // string array

这很好用,但是有大量的冗余。我知道我不能扩展类型,但是是否有类似的技巧

Possible to extend types in Typescript?

这将允许我在声明func1时使用一个func2类型声明?

1 个答案:

答案 0 :(得分:1)

您只能使用new support for tuple types as rest parameter types in TypeScript 3.0来做到这一点:

type F<Rest extends any[], R> =
    (a: string, b: string, c: string, d: string, e: string, f: string, ...rest: Rest) => R;
type func1 = F<[], string>;
type func2 = F<[true], string[]>;