【问题标题】:How do I write the signature for a function where the argument types are dependent?如何为参数类型依赖的函数编写签名?
【发布时间】:2022-01-10 07:34:36
【问题描述】:

有没有一种类型安全的方式来表达这个函数?在此示例中,我添加了数字,但问题是关于一般模式。

type signature = 
    ((a: number, b: number) => number) & 
    ((a: bigint, b: bigint) => bigint);

// Operator '+' cannot be applied to types 'number | bigint' and 'number | bigint'.
const add : signature = (a, b) => a + b; 

这两个参数可以是两种不同的类型,但绝不能同时是两种。有没有办法编写这个函数类型让它工作?

【问题讨论】:

  • 相关,可能足够接近骗子-stackoverflow.com/q/59745527我还没有找到好方法
  • 这很不幸。这可能会有所不同,因为不涉及类型保护。
  • this

标签: typescript types


【解决方案1】:

您可以定义所有方法类型,然后定义一个方法来处理所有已定义的类型。


function add(a: {option1:string}, b: number): number
function add(a: number, options: { option2: number }): number
function add(a: string, b: string, options: { options3: boolean }): number
function add(
    a: string | number|{option1:string},
    b: string | number | { option2: number }, 
    c: { options3: boolean } = {options3: false}
) {
    // todo
    return 0;
}

add({option1:'a1'},2)
add(1,{option2:2})
add('a','b',{options3:false})
function add(a: number, b: number): number
function add(a: bigint, b: bigint): bigint
function add(a: any, b: any): number | bigint {
    return a + b;
}

或使用泛型类型


function add<T extends (string|number|bigint)>(a: T, b: T): T {
    return a as any + b;
}
add('a','b');
add(1,2);
add(1,'b'); // error

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多