Home > Back-end >  How to create an interface that infers the correct type contextually
How to create an interface that infers the correct type contextually

Time:04-16

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

CodePudding user response:

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

  • Related