Issue
So, I want to have some posibility to provide type assistance, when I have some function calls like in example below. I want to check if first and second argument has same value.
myfn(12333, 12333); // To be OK
myfn(12333, 222); // To FAIL
myfn({
val_1: 12333,
val_2: 12333,
}); // To be OK
myfn({
val_1: 12333,
val_2: 222,
}); // To FAIL
For some small amount of values, ("error", "warning", ...etc), I can make an override, but for numbers it's makes no sense.
Solution
This is how you could type it. The Narrow-Type infers the value of your arguments. By using two generics you prevent the widening for T from {a:12,b:23} to 12|23
export type Narrowable = string | number | bigint | boolean;
export type Narrow<A> =
| (A extends Narrowable ? A : never)
| (A extends [] ? [] : never)
| {
[K in keyof A]: A[K] extends Function ? A[K] : Narrow<A[K]>;
};
declare function myfn<T,U extends T>(a: Narrow<T>, b: U): any
declare function myfn<T,U extends T>(a: Narrow<{ val_1: T, val_2: U }>): any
Answered By - Filly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.