在TypeScript中映射类型的特定属性上设置类型
我正在尝试在TypeScript中为我们从JavaScript转换过来的东西创建一个类型 基本上,类型是一个标准的对象文字,其中每个子对象都是相同类型的重复。但是,如果它是'\u errors'属性,那么它应该是另一种类型的数组,并且是可选的 这在TypeScript中可能吗 这就是我想要的,但是下面的语法是无效的在TypeScript中映射类型的特定属性上设置类型,typescript,Typescript,我正在尝试在TypeScript中为我们从JavaScript转换过来的东西创建一个类型 基本上,类型是一个标准的对象文字,其中每个子对象都是相同类型的重复。但是,如果它是'\u errors'属性,那么它应该是另一种类型的数组,并且是可选的 这在TypeScript中可能吗 这就是我想要的,但是下面的语法是无效的 // This is invalid but might demonstrate what I'm after... type MyType = { _errors?: E
// 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
}]
}
}
也许我错了,但我认为这在今天是不可能的。我试过:
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
}]
}
};
接口错误包装器{
消息:字符串;
映射:布尔;
}
类型错误映射={
[P in keyof T]:部分和错误映射;
};
接口SomeObj{
物业1:{
属性1A:编号;
属性1b:字符串;
};
属性2:编号;
}
声明let x:ErrorMap;
//自动完成按预期工作
console.log(x.property1.property1a.\u错误);
console.log(x.property1.property1b.\u错误);
console.log(x.property2.\u错误);
//错误
让myObject:ErrorMap={
物业1:{
物业1A:{
_错误:[{
消息:“字符串消息”,
映射:false
}, {
消息:“字符串消息”,
映射:false
}]
},
物业1B:{
_错误:[{
消息:“字符串消息”,
映射:false
}]
}
},
物业2:{
_错误:[{
消息:“字符串消息”,
映射:false
}]
}
};
我认为映射类型中需要一个条件,但是