Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
How to create an interface that infers the correct type contextually

So below i have an example of what I'd like to do. I want to be able to initialize an empy list of the DbTransactInput and push objects onto the array.

I tried messing with mapped types to get the "Items" in the "Put" property to correctly infer the data type (not looking for a union type) but anything I tried with generics was impossible to instantiate with an empty list and have it dynamically infer after the fact.


export interface DbTransactWriteInput {
  Delete?: {
    TableName: keyof DbTableData;
  };
  Put?: {
    TableName: keyof DbTableData;
    Item: DbTableData[keyof DbTableData];
  };
  Update?: {
    TableName: keyof DbTableData;
  };
}

export async function transactWrite(
  input: DbTransactWriteInput[]
): Promise<void> {
  await db.transactWrite({ TransactItems: input }).promise();
}

interface ITableAData {
    test1: "A",
    a: "tableA",
}

interface ITableBData {
    test2: "B",
    b: "tableB"
}

interface ITableCData {
    test3: "C",
    c: "tableC"
}

export interface DbTableData {
  "TableA": ITableAData;
  "TableB": ITableBData;
  "TableC": ITableCData;
}

const transactList: DbTransactWriteInput[] = []
transactList.push({
    Put: {
        TableName: "TableA",
        Item: { // How to get Item to infer type ITableAData given TableName of "TableA"?
            test1: "A",
            a: "tableA"
        }
    }
})

Playground Link: Provided

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use a mapped type to generate possible values for Put:

export interface DbTransactWriteInput {
  Delete?: {
    TableName: keyof DbTableData;
  };
  Put?: PossiblePuts<DbTableData>
  Update?: {
    TableName: keyof DbTableData;
  };
}

type PossiblePuts<Data> = {
  [K in keyof Data]: {
    TableName: K;
    Item: Data[K];
  }
}[keyof Data];

Playground

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda