-2

I would like to do something like this:

interface Apple {
  type: string;
  color: string;
}

type RealApple = WithConcat<Apple, 'type', 'color'>;

So that the resulting type of RealApple is:

type RealApple = {
  type: string;
  color: string;
  'type#color': string;
}

Is this possible? How could I implement WithConcat? The reason is to handle types when talking to the database, where a composite sort key is created from two other fields which don't really have that composite on the schema.

2 Answers2

0

What about having a class that implements your interface?

interface Apple {
    type: string;
    color: string;
}

class RealApple implements Apple {
    constructor(public type: string = "", public color: string = "") {
    }

    // this is the equivalent of your composite key.
    public get typeAndColor(): string {
        return `${this.type}_${this.color}`;
    }

    public static fromApple(apple: Apple): RealApple {
        return new RealApple(apple.type, apple.color);
    }
}

const apple: RealApple = RealApple.fromApple({
    type: "braeburn",
    color: "red"
});

apple.typeAndColor; // braeburn_red
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
0

Here's the solution that I came up with, which is not a typescript type directly but accomplishes what I needed:

function withConcat<T>(item: T, field1: keyof T, field2: keyof T) {
  return {
    ...item,
    [`${field1}#${field2}`]: `${item[field1]}#${item[field2]}`
  }
}