Shasak
Shasak

Reputation: 820

In Typescript how to define a function type that allows arbitrary preceding params before a required param?

I want to define a function type that allows arbitrary arguments preceding a required argument example:

type Op = (...args, required: A) => void

I am hoping to have behaviour of the following kind:

const foo:Op = (a.b,c, required: A) => void // this should compile
const foo:Op = (a.b,c:A) => void // this should compile
const foo:Op = (a.b,c) => void // this should not compile

I tried:

type Op = (required:A) => string 

but these throw a type mismatch error:

let foo: Op = (a, b:A) => {return ""} //error
let foo: Op = (a, required:A) => {return ""} // error

I tried other ways of defining the type hoping to get lucky

type Op = (...args: any[], required:A) => string //error 

interface Op {
  (...args: any[], required:A): string //error
}

none of them worked.

Is there a way to do this in Typescript? Or am I trying something that is conceptually irreconcilable?

Upvotes: 2

Views: 185

Answers (1)

Martin Stone
Martin Stone

Reputation: 13027

I think you're out of luck. Even doing something like this...

interface A {
    x: number
}

type Op = ((a, b, c, required: A) => string) 
        | ((a, b, required: A) => string) 
        | ((a, required: A) => string) 
        | ((required: A) => string);


let foo: Op = (a, b:A) => "";
let bar: Op = (a, b:number) => ""; // not an error :-(

... won't work because missing parameters don't fail the type check.

Upvotes: 1

Related Questions