Let say I have that code:
type MyStr = "one" | "two" | "three";
const x: MyType<MyStr> = { master: "one", slave: "one" }; // should compile
const y: MyType<MyStr> = { master: "one", slave: "two" }; // should not compile
My goal is to create a type MyType that force the slave to be the same type as the master.
One solution is to do this:
type MyType<T extends string> = {
[K in T]: { master: K, slave: K }
}[T];
The idea is to create all posibilitties, having all versions:
type MyType<T extends string> = {
[K in T]: { master: K, slave: K }
};
// MyType<"one" | "two" | "three"> = {
// "one": { master: "one", slave: "one" },
// "two": { master: "two", slave: "two" },
// "three": { master: "three", slave: "three" },
// }
And taking that type at index of T gives the one we chose.
This approach works but when having a lot of fields, then typescript server is overloaded and die.
Is there a better option to achieve this?
Of course this is just a demonstration of the problem and my real problem is to create something like this:
type ElementFieldType<T, K extends keyof T> = {
name: K;
Element: FC<{ value: T[K], onChange: (value: T[K]) => void }>;
}
So I need that K will be forced to be the same type in name
and in value of Element
, meaning once name
have been set to some key, Element
is forced to be the type that handles that key