-2

我想做这样的事情:

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

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

所以得到的类型RealApple是:

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

这可能吗?我该如何实施WithConcat?原因是在与数据库对话时处理类型,其中复合排序键是从其他两个字段创建的,这些字段在架构上实际上没有该复合。

4

2 回答 2

0

拥有一个实现你的接口的类怎么样?

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
于 2020-06-15T22:29:56.873 回答
0

这是我想出的解决方案,它不是直接的打字稿类型,而是完成了我需要的:

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

于 2020-06-15T23:03:34.407 回答