【问题标题】:Can a typescript type be created that concatenates two fields?可以创建连接两个字段的打字稿类型吗?
【发布时间】:2020-10-05 09:23:01
【问题描述】:

我想做这样的事情:

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

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

所以RealApple 的结果类型是:

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

这可能吗?我怎样才能实现WithConcat?原因是在与数据库通信时处理类型,其中复合排序键是从其他两个字段创建的,而这些字段在架构上实际上并没有该复合。

【问题讨论】:

    标签: typescript graphql amazon-dynamodb aws-amplify graphql-codegen


    【解决方案1】:

    如果有一个实现你的接口的类呢?

    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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-27
        • 2021-12-13
        • 2022-08-11
        • 2021-05-01
        • 1970-01-01
        • 2023-01-09
        • 2020-09-14
        • 2018-10-17
        相关资源
        最近更新 更多