My situation involves a generic container type that can hold various types of data. The data's type is determined at runtime by a "type" field that contains a string:
type Type = "Numeric" | "Text";
type DataTypeFor<T extends Type> =
T extends "Numeric" ? number
: T extends "Text" ? string
: never;
interface Container<T extends Type> {
type: T;
data: DataTypeFor<T>;
}
But, there seems to be an issue with the type inference for the data
field when operating on an instance of this interface:
function operate<T extends Type>(container: Container<T>) {
switch (container.type) {
case "Numeric":
// Error
const a: number = container.data;
console.log(a);
break;
case "Text":
// Error
const b: string = container.data;
console.log(b);
break;
case "Fsasefsef":
// No error here! Why?
break;
}
}
I seem to have a misunderstanding about how type inference works with generics in scenarios like these.
Is there a way to achieve the desired pattern in this context?