如何安全地引用 Typescript 中对象的参数化 属性?

How to safely refer to a parameterised property of an object in Typescript?

我有一个函数接收一个对象作为参数并访问它的一个属性,由另一个参数决定。像这样:

// js code
function setProperty(subject, property, value) {
    subject[property] = value;
}

如何以确保 property 参数是 subject 参数的键且 value 参数具有相同类型的方式对该函数进行类型注释?

如果有帮助,我希望 property 参数始终是文字值(“硬编码”值,而不是变量),因此这是一个可接受的约束。

您可以使用泛型、extendskeyof 来实现此类功能。例如:

interface Subject {
    a: string,
    b: number
}

function setProperty<T extends keyof Subject>(subject: Subject, property: T, value: Subject[T]) {
    subject[property] = value;
}

const test: Subject = { a: 'test', b: 2 };

setProperty(test, 'b', 'test'); // Won't compile: Argument of type 'string' is not assignable to parameter of type 'number'.