1

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

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

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

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

4

1 回答 1

2

您可以使用泛型、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'.
于 2021-10-08T01:02:56.663 回答