泛型类型:动态类型检查特定对象属性:在泛型类型B中使用类型A中的键~值对



我目前有一个类型(FieldTypeProperties(,当它的键传递给函数或对象时,我想强制执行动态类型检查:

export enum supportedFields{
Text = "Text",
Note = "Note",
Number = "Number"
}
export type FieldTypeProperties = {
[supportedFields.Text]: TypeA;
[supportedFields.Note]: TypeB;
[supportedFields.Number]: TypeC;
};

我已经成功地定义了一个行为如预期的函数:

const createField = <K extends keyof FieldTypeProperties>(fieldType: K, properties: FieldTypeProperties[K]): IResult => {
let field: IResult;
//Some code
return field;
}

用法按预期工作,fieldType参数值确实检查了属性参数中的正确类型:

let test = createField(supportedFields.Note, {});
// Checks for Type B in the properties argument, as defined in the FieldTypeProperties type

然而,对于批处理操作,我希望循环一个符合createField((中参数的对象数组,因此:

type BatchObj<K extends keyof FieldTypeProperties> = {
fieldType: K;
properties: FieldTypeProperties[K];
}
// Intended Usage:
let testBatch1: BatchObj<keyof FieldTypeProperties>[] = [
{
fieldType: supportedFields.Text,
properties: {}, //Type A should only be checked, but it's not, instead a union of TypeA | TypeB | TypeC is checked
},
]
// Usage that works but is NOT desired:
let testBatch2: BatchObj<supportedFields.Text>[] = [
{
fieldType: supportedFields.Text,
properties: {}, //Type A is checked, but now any additional objects added to this array must have a fieldType = supportedFields.Text and properties = TypeA
}
]

我能理解为什么会发生这种情况,因为在testBatch1中:fieldType(K(将是FieldTypeProperties类型的键集,而properties(FieldTypeProperties[K](将是FieldTypeProperties类型

值集有没有一种方法可以根据上面代码片段中推断的内容来实现我想要的用途?或者这是打字稿的限制,而就目前情况来看,这是不可能的?

我们将非常感谢您的回复:(

您可以使用条件类型的分布为每个可能的键生成一个并集:BatchObj<"Text"> | BatchObj<"Note"> | BatchObj<"Number">。这将确保fieldTypeproperties之间的关系得到保留:

type BatchObj<K extends keyof FieldTypeProperties> = {
fieldType: K;
properties: FieldTypeProperties[K];
}
type BatchObjUnion<K extends keyof FieldTypeProperties = keyof FieldTypeProperties>  = K extends K ? BatchObj<K>: never
// Intended Usage:
let testBatch1: BatchObjUnion[] = [
{
fieldType: supportedFields.Text,
properties: { text: "" }, //Type A
},
]

游乐场链接

最新更新