-1

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.

Profesor08
  • 1,181
  • 1
  • 13
  • 20
  • In your first code block, the function has two parameters but in the second one it takes just one object with two properties. Is that intentional? – Tobias S. Aug 31 '22 at 12:27
  • 2
    What's the point of this function? – kelsny Aug 31 '22 at 12:51
  • @kelly I'm just asking about posibility to achieve this. Generic `fn(T, T)` just checks type to be the same. But how about values? – Profesor08 Aug 31 '22 at 15:04
  • Does this answer your question? [Javascript - deepEqual Comparison](https://stackoverflow.com/questions/25456013/javascript-deepequal-comparison) – Tobias S. Aug 31 '22 at 15:07

1 Answers1

1

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
Filly
  • 411
  • 2
  • 8
  • 1
    Cool. I didn't think it was possible, but it works. Together with this (https://stackoverflow.com/a/59906630/3654943), finaly I can generate interesting things. ```typescript function table( arr1: FixedArray>, arr2: FixedArray, ): void {} ``` – Profesor08 Sep 02 '22 at 07:28