Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda