TrevTheDev
TrevTheDev

Reputation: 2737

How to enforce type compliance on callback parameters

How would one get foobar(fn) below to error as property b is missing from the arg parameter type of bar?

const foo = (arg: {a: any,b: any})=>1

const foobar = <T extends typeof foo>(arg:T)=>1

const bar = (arg: {a: string})=>1

// how would one type this so that `bar` is 
// flagged as invalid, because prop `b` is missing?
foobar(bar)  

code

To my human brain bar doesn't extend foo - I believe this is happening due to contravariance but I'm still ignorant, hence the question.

Upvotes: 3

Views: 56

Answers (1)

tenshi
tenshi

Reputation: 26344

Extremely useful type that we'll need (from here):

type Equals<T, U> =
  (<G>() => G extends T ? 1 : 2) extends
  (<G>() => G extends U ? 1 : 2) ? true : false;

Then you can just check if T is equal to the type of foo:

const foobar = <T extends typeof foo>(arg: Equals<T, typeof foo> extends true ? T : never)=>1

and if it is, it should be T, otherwise never.

Seems to work!

Playground

Upvotes: 2

Related Questions