【问题标题】:Typescript enforce function accepts first argument打字稿强制函数接受第一个参数
【发布时间】:2022-01-26 18:36:36
【问题描述】:

我想强制特定函数接受特定类型的第一个参数

type MyFunc = <Args extends []>(channelId: string, ...args: Args) => string

const doThing: MyFunc = (channelId: string, arg1: number, arg2: string) => arg1 + arg2

我收到以下错误

Type '(channelId: string, arg1: number, arg2: string) => string' is not assignable to type 'MyFunc'.
  Types of parameters 'arg1' and 'args' are incompatible.
    Type 'Args' is not assignable to type '[arg1: number, arg2: string]'.
      Type '[]' is not assignable to type '[arg1: number, arg2: string]'.
        Source has 0 element(s) but target requires 2.

Playground link

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    你会这样做,但是......

    您确定要连接数字和字符串(并且不使用channelId 参数)吗?

    TS Playground

    type MyFunc<Params extends readonly unknown[]> = (channelId: string, ...params: Params) => string;
    
    const doThing: MyFunc<[n: number, str: string]> = (channelId, arg1, arg2) => arg1 + arg2;
    
    const result = doThing('my_channel_id', 42, 'hello world');
    console.log(result) // "42hello world"
    

    【讨论】:

    • 哦,你可以忽略实现,这只是一个例子,谢谢!
    • @david_adler 所以这回答了问题?
    • 仍在检查,因为我可能需要推断您静态设置的通用参数,因此将返回答案
    • 如果我误解了问题中的某个细节,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    相关资源
    最近更新 更多