I'm currently diving into Typescript and exploring how to dynamically set object types based on specific keys (using template literals).
Check out the code snippet below:
interface Circle {
radius: number;
}
interface Square {
length: number;
}
type TypeName = "circle" | "square";
type ObjectType<T> =
T extends "circle" ? Circle :
T extends "square" ? Square :
never
type Shape = {
[id: `${TypeName}.${string}`]: ObjectType<TypeName>
}
const circle:Shape = {"circle.anythig": {length: 33}} // Square??
// ^^^^^^ how to force the type based on object property key name?
const square:Shape = {"square.anythig": {length: 33}} // Square