具有单独的args作为不带索引器但具有计算出的属性名称的对象的键/值的函数

时间:2018-11-29 14:30:39

标签: typescript overloading computed-properties

我试图在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

0 个答案:

没有答案