0

I would like to enforce that a particular function accepts a first argument of a particular type

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

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

I get the following error

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

1 Answer 1

1

This is how you'd do it, but...

Are you sure you want to concatenate a number and a string (and not use the channelId argument)?

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Oh you can ignore the implementation it's just an example, thanks!
@david_adler So this answered the question?
still checking, as I might need to infer the generic parameter you've statically set so will circle back to the answer
If it turns out that I misunderstood a detail in the question, just let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.