Pesquisa de site

typescript - Como definir valores do objeto com base em propriedade/chave


Estou aprendendo Typescript e tentando entender como definir o tipo de objeto com base na chave (template literal)

Aqui está o exemplo:

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 

Parque infantil

Resposta #1

Você pode usar um tipo mapeado com remapeamento de chave para associar um dado TypeName ao seu correspondente ObjectType.

type Shape = {
    [ID in TypeName as `${ID}.${string}`]: ObjectType<ID>
}

Isso levará ao erro desejado se os tipos não corresponderem.

const shape: Shape = { 
  "circle.anything": { length: 33 },
                   //  ^^^^^^ Type '{ length: number; }' is not assignable to type 'Circle'
  "square.anything": { length: 33 }
}

Parque infantil

Resposta #2

Aqui está outra implementação, se alguém estiver interessado:

interface Circle {
  radius: number;
}

interface Square {
  length: number;
}

type Shapes = {
  circle: Circle
  square: Square
}

type TypeName = "circle" | "square"; 

type Shape = {
    [ID in keyof Shapes as`${ID}.${string}`]: Shapes[ID]
}

const t:Shape = {"square.foo": {length: 33}}