typescript - 根据参数区分返回类型

标签 typescript

我正在尝试键入一个接受字符串或字符串[] 并分别返回 bool 值或 bool 值[] 的函数。我尝试过使用泛型类型和重载,但两者似乎都会引发某种错误:

// generic way
function genericWay<T extends string | string[]>(val: T): T extends string ? boolean : boolean[] {
    if (typeof val === 'string'){
        return true // Type 'true' is not assignable to type 'T extends string ? boolean : boolean[]'
    }
    return [true] // Type 'true[]' is not assignable to type 'T extends string ? boolean : boolean[]'
}

const a1 = overloadWay('bbb')
const a2 = genericWay(['bbb'])
const a3 = genericWay(5333) // should throw error


// overload way
function overloadWay(val: string[]): boolean[]; // This overload signature is not compatible with its implementation signature.
function overloadWay(val: string): boolean {    
    if (typeof val === 'string'){
        return true
    }
    return [true] // Type 'boolean[]' is not assignable to type 'boolean'.
}

const b1 = overloadWay('bbb')
const b2 = overloadWay(['bbb'])
const b3 = overloadWay(5333) // should throw error

ts playground

  1. 从第一个示例来看 - 似乎我的返回类型不正确?
  2. 对于重载方式,出于某种原因,它没有通过类型检查来区分两种输入类型。

最佳答案

由于另一个答案已经提供了如何以通用方式修复警告,这需要显式类型转换,下面是如何使用函数重载来实现相同的目标。

您的重载方式定义不正确。您需要在函数之前指定所有重载,并且实现函数应在其签名中包含所有可能的输入和输出。您可以在实现中求助于 any,但我认为只要您可以避免,这都是不可取的。

这里是重载的方式

// overload way
function overloadWay(val: string[]): boolean[];
function overloadWay(val: string): boolean ;
function overloadWay(val: string| string[]): boolean | boolean[] {    
    if (typeof val === 'string'){
        return true
    }
    return [true]
}

// b1 is boolean
const b1 = overloadWay('bbb')

// b2 is boolean[]
const b2 = overloadWay(['bbb'])

// shows error
const b3 = overloadWay(5333) 

TS Playground

关于typescript - 根据参数区分返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65896206/

相关文章:

angular - Angular 中的主题在 500 内部错误后停止工作

javascript - 帕斯卡大小写(或大驼峰大小写)但允​​许使用像 HTMLInputElement 这样的名称?

javascript - VueJS 中的 For 循环与对象数组中的 TypeScript

typescript - 将 firebase 链式方法重写为 promise.all

javascript - 尝试从 Angular 6 中的输入访问值时,Event 和 event.target 的正确类型是什么?

angular - 如何等待 FirebaseListObservable 的响应

node.js - Rollup 不捆绑声明文件

angular - 通过重定向登录后,Firebase Datasnapshot Observable 未立即更新

javascript - 在 typescript 中添加等待/异步抛出无法解析 'imports'

javascript - 类型 'Ref<x>' 的参数不可分配给类型 'x' 的参数