Reputation: 2737
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)
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
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!
Upvotes: 2