是否可以根据另一个参数动态限制参数类型?
type Foo = {
bar: string;
baz: number;
}
let o: Foo;
function setProperty(key: keyof Foo, value: Foo[keyof Foo]) {
o[key] = value;
}
setProperty("bar", 55); // shouldn't be allowed
setProperty("bar", "55"); // allowed
答案 0 :(得分:2)
将lookup types与泛型一起使用:
type Foo = {
bar: string;
baz: number;
}
let o: Foo;
function setProperty<P extends keyof Foo> (key: P, value: Foo[P]) {
o[key] = value;
}
setProperty("bar", 55); // Throws error
setProperty("bar", "55"); // allowed