我可以使用Typescript函数来返回标量或数组值,而调用方不需要转换输出

时间:2018-08-27 12:29:02

标签: typescript

问题

我有这个功能:

save<T>(x: T | T[]) {
 if (x instanceof Array) {
     // save array to db
 } else {
     // save entity to db
 }
 return x
}

// client code
let o: SomeType = { // values here }
let updated = save(o) // compile confusion... 

TS不知道updated是单数还是数组。

问题

如何定义函数,以便:

  • 如果传递了单个参数,则打字稿会知道结果是单个
  • 如果传递了数组参数,则打字稿会知道结果是数组

1 个答案:

答案 0 :(得分:3)

从定义中删除T[]T[]T的子集。

function save<T>(x: T): T {
    if (x instanceof Array) {
        // save array to db
    } else {
        // save entity to db
    }

    return x
}

// client code
let a: SomeType = { // values here };
let updateda = save(a); // updateda is of type SomeType

let b: SomeType = { // values here };
let updatedb = save([a, b]); // updatedb is of type SomeType[]