代码之家  ›  专栏  ›  技术社区  ›  cjones26

有没有更好的方法来定义“包装”的JSON对象而不违反TS原则?

  •  0
  • cjones26  · 技术社区  · 7 年前

    我最近开始使用TypeScript,遇到了一个问题,我很好奇TypeScript是否提供了任何功能。我正在联系一个web服务,该服务接受以下格式的数据请求:

    {
        "data": {
            "country": "US"
            "customerType": "Internal"
            "customer": "ABC"
        }
    }
    

    export class CalculatorRequest {
        data: CalculatorRequestData
    }
    
    export class CalculatorRequestData {
        country: string;
        customerType: string;
        customer: string;
    }
    

    有什么方法可以避免使用类型为“CalculatorRequestData”的二级内部数据类吗?

    我知道我可以精心设计我的请求,以避免需要内部类,但我想看看是否有更有效的选择。

    1 回复  |  直到 7 年前
        1
  •  1
  •   user47589 user47589    7 年前

    使用泛型只允许创建“数据”对象,而只需要一个“请求”对象。

    export class ApiRequest<T> {
        data: T
    }
    
    export class CalculatorRequestData {
        country: string;
        customerType: string;
        customer: string;
    }
    
    // no extra request object needed, regardless of how many requests you have
    export class FoooData {
        foo: string;
        bar: number;
    }