Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!