我试图在setState
函数中使用计算的属性名称,其中第一个arg是IState
接口的键,第二个arg是IState
接口的值。如果第一个arg是某个键,则该值必须是某个值。我本以为在下面使用这样的重载,但是Typescript给了我错误。我现在没有可用的错误,但这看起来正确吗:
enum Qux = {
qux1 = 'qux1',
qux2 = 'qux2'
}
enum Foo = {};
enum Bar = {};
interface IState = {
isLoading: boolean,
foo?: Foo,
bar?: Bar,
qux?: Qux
}
interface IHandleTargetChange {
(input: 'bar', value: Bar): void;
(input: 'qux', value: Qux): void;
}
class MyComponent extends React.Component {
handleTargetChange: IHandleTargetChange = (input: any, value: any) => {
this.setState({
[input]: value
});
}
}
它突出显示{ [input]: value }
并给出错误:
[ts]
Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'Pick<IState, "isLoading" | "foo" | "bar" | "qux">'.
Property 'isLoading' is missing in type '{ [x: number]: any; }'. [2345]
(parameter) inputName: any