我想做这样的事情:
interface Apple {
type: string;
color: string;
}
type RealApple = WithConcat<Apple, 'type', 'color'>;
因此,RealApple
的最终类型为:
type RealApple = {
type: string;
color: string;
'type#color': string;
}
这可能吗?如何实施WithConcat
?原因是在与数据库对话时要处理类型,其中从其他两个在字段上实际上没有该复合键的字段创建复合排序键。
答案 0 :(得分: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
答案 1 :(得分:0)
这是我想出的解决方案,它不是直接的打字稿类型,而是可以满足我的需要:
function withConcat<T>(item: T, field1: keyof T, field2: keyof T) {
return {
...item,
[`${field1}#${field2}`]: `${item[field1]}#${item[field2]}`
}
}