gpt4 book ai didi

typescript - 在 TypeScript 中推断接口(interface)属性类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:15 24 4
gpt4 key购买 nike

假设我有这个接口(interface)和一个包含该类型的对象:

interface IMyData {
a: TypeA;
b: TypeB;
c: boolean;
d: string;
}

const myObj: { data: IMyData } = {
data: {
a: someValueA,
b: someValueB,
c: true,
d: "someValueD"
}
}

现在我想从该对象获取单个属性并让函数推断返回类型:

function getField(obj: { data: IMyData }, field: keyof IMyData){
return obj.data[field];
}

const myFieldStr = getField(myObj, "d"); // should infer type string
const myFieldBool = getField(myObj, "c"); // should infer type boolean

如何定义 getField 函数以便它推断返回类型?现在它会推断 TypeA | B型 | bool |字符串.


这是另一个(更复杂?)场景:

interface IMyValue<T> {
value?: T;
}

interface IMyData2 {
a?: IMyValue<string>;
b?: IMyValue<number>;
c?: IMyValue<boolean>;
d?: IMyValue<string>;
}

function getValue<T extends keyof IMyData2>(field: T, data: IMyData2) {
return data[field] ? data[field]!.value : undefined; // this wouldn't compile without '!' mark
}

const testData: IMyData2 = {
a: { value: 'a' },
b: { value: 2 },
c: { value: false },
};

const testValue1 = getValue('a', testData); // i want this to detect as type of `string`
const testValue2 = getValue('b', testData); // i want this to detect as type of `number`
const testValue3 = getValue('b', testData); // i want this to detect as type of `boolean`
const testValue4 = getValue('b', testData); // i want this to detect as type of `undefined`

最佳答案

您必须告诉类型系统 field 的确切字面值。最简单的方法是使用像这样的通用函数:

interface IMyData {
c: boolean;
d: string;
}

const myObj: { data: IMyData } = {
data: {
c: true,
d: "someValueD"
}
}

function getField<T extends keyof IMyData>(obj: { data: IMyData }, field: T){
return obj.data[field];
}

const myFieldStr = getField(myObj, "c"); // should infer type boolean
const myFieldBool = getField(myObj, "d"); // should infer type string

或者在最简单的一般情况下:

function pluck<T, K extends keyof T>(obj : T, key : K) {
return obj[key];
}

const foo = pluck({ bar: "asd", baz: 5 }, "bar"); // infers string

关于typescript - 在 TypeScript 中推断接口(interface)属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57930976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com