首页 > 解决方案 > 根据另一个字符串属性的值解析一个属性的动态类型

问题描述

嗨,我不确定是否可能,但如果不可能,请建议我一些替代方法来实现它。

我想在接口中设置对象属性的类型,其中对象可能具有任何属性,但必须具有以该接口中另一个属性的值命名的属性。让我们考虑案例

interface ListGroupProps {
  data: {[x:string]:any} & {[valueProperty]:any};
  valueProperty:string;
}

现在考虑一个具有有效类型的对象

{
    data:{id:1, textValue: "hello world"},
    valueProperty: "textValue",
}

这是一个类型无效的对象

{
    data:{id:1, textValue: "hello world"}, // someOtherPropertyName in not present here
    valueProperty: "someOtherPropertyName",
}

如果可能的话最好不要通用类型

标签: typescripttypescript-typingstypescript-generics

解决方案


这是可能的,但您必须使用泛型:

interface ListGroupProps<K extends (string extends K ? never : keyof any)> {
    data: { [x: string]: any } & { [x in K]: any };
    valueProperty: K;
}

const x: ListGroupProps<'textValue'> = {
    data: { id: 1, textValue: "hello world" },
    valueProperty: "textValue",
} as const;

const y1: ListGroupProps<'textValue'> = {
    data: { id: 1, textValue: "hello world" },
    valueProperty: "someOtherPropertyName", // Error on `valueProperty`
};

const y2: ListGroupProps<'someOtherPropertyName'> = {
    data: { id: 1, textValue: "hello world" }, // Error on `data`.
    valueProperty: "someOtherPropertyName",
};

const y3: ListGroupProps<string> = { // Error on `string`.
    data: { id: 1, textValue: "hello world" },
    valueProperty: "someOtherPropertyName",
};

游乐场链接


推荐阅读