在TypeScript中设置映射类型的特定属性的类型

时间:2017-06-08 11:30:59

标签: typescript

我正在尝试在TypeScript中创建一个类型,用于我们从JavaScript转换的内容。

基本上,类型是标准对象文字,其中每个子节点都是相同类型的重复。但是,如果它的“错误”是属性应该是另一种类型的数组,并且是可选的。

这在TypeScript中是否可行?

这是我之后的事情,但下面的语法无效。

// This is invalid but might demonstrate what I'm after...
type MyType = { 
    _errors?: ErrorWrapper[]; // Anything using the key '_errors' should be an array of ErrorWrapper. But this should be optional.
    [key: string]: MyType; // Any other properties should be MyType.
 };

interface ErrorWrapper {
    message: string;
    mapped: boolean;
}

在JavaScript中,对象看起来像这样:

let myObject = {
  property1: {
    property1a: {
       _errors: [{
          message: 'string message',
          mapped: false
       },{
          message: 'string message',
          mapped: false
       }]
    },
    property1b: {
       _errors: [{
          message: 'string message',
          mapped: false
      }]
    }
  },
  property2: {
       _errors: [{
          message: 'string message',
          mapped: false
      }]
  }
}

1 个答案:

答案 0 :(得分:0)

也许我错了,但我认为今天不可能。我尝试过:

interface ErrorWrapper {
    message: string;
    mapped: boolean;
}

type ErrorMap<T> = {
    [P in keyof T]: Partial<{ _errors: ErrorWrapper[] }> & ErrorMap<(Partial<T[P]>)>;
};

interface SomeObj {
    property1: {
        property1a: number;
        property1b: string;
    };
    property2: number;
}

declare let x: ErrorMap<SomeObj> ;

// Autocomplete works as expected
console.log(x.property1.property1a._errors);
console.log(x.property1.property1b._errors);
console.log(x.property2._errors);

// Error
let myObject: ErrorMap<SomeObj> =  {
  property1: {
    property1a: {
       _errors: [{
          message: "string message",
          mapped: false
       }, {
          message: "string message",
          mapped: false
       }]
    },
    property1b: {
       _errors: [{
          message: "string message",
          mapped: false
      }]
    }
  },
  property2: {
    _errors: [{
        message: "string message",
        mapped: false
    }]
  }
};

我认为我们需要映射类型中的条件,但that feature is not available yet