My dilemma revolves around defining a type/interface for a collection of properties where each property has a specified type. You can reference Props
in the code snippet below for clarification.
The goal is to create a type that represents a tuple <A, B>
, with A
being the name of one property and B
being the corresponding property value type.
For instance, ['someStr', 'a']
should meet the criteria, while ['someStr', 1]
should not since, based on Props
, 1
must be a string.
To illustrate, consider the following experimental code:
interface Props {
someStr: string;
someNum: number;
}
type FuncWithPropInput = <T extends keyof Props>(key: T, value: Props[T]) => [typeof key, typeof value];
// The compiler infers `T` from `key`, so manual specification is unnecessary.
const workWithProps: FuncWithPropInput = (key, value) => [key, value];
workWithProps('someStr', 'a'); // No error, as expected.
workWithProps('someStr', 5); // Error regarding the incorrect type of `5`, as expected.
workWithProps('foobar', 5); // Error due to `'foobar'` not being in the collection, as expected.
type TupleWithPropKeyAndValue<T extends keyof Props> = [
T,
Props[T]
];
// Surprisingly, it complains about missing type argument `T`.
const var1: TupleWithPropKeyAndValue = [
'someStr',
5 // Unexpectedly, no error shown here.
];
const var2: TupleWithPropKeyAndValue<'someStr'> = [
'someStr',
5 // Expected error message about `5` needing to be a string.
];
const var3: ReturnType<FuncWithPropInput> = [
'someStr',
5 // Surprisingly, no error displayed here either.
];
I find it puzzling that FuncWithPropInput
works correctly in the example above, yet TupleWithPropKeyAndValue
encounters issues.
Ultimately, I aim to write something similar to the case of var1
and prompt TypeScript to flag an error for 5
needing to be a string.
Furthermore, given the successful behavior of FuncWithPropInput
, the discrepancy with var3
failing leaves me perplexed.