该表达式不可调用类型“String”没有调用签名

bor*_*ort 18 javascript typescript reactjs redux

在我的 Typescript 函数中,当我将类型注释设置为 String 时,我收到错误“此表达式不可调用,类型‘String’没有调用签名。” 如下面的代码所示。

function thing<T>(setThingState: string ){

    return Axios.request({
        method: 'get',
        url:'https://jsonplaceholder.typicode.com/todos/',//'https://jsonplaceholder.typicode.com/todos/'
    }).subscribe(
        response => {
            console.log(response);
            setThingState({ message: response.status });
        },
        error => {
            console.log(error);
            setThingState({ message: '404' });
        }
    );

}
Run Code Online (Sandbox Code Playgroud)

但是,如果我将类型设置为 Any,那么就没有问题。如下面的代码所示。我仍然对 TypeScript 很感兴趣,所以任何反馈都将不胜感激。

function thing<T>(setThingState: any ){

    return Axios.request({
        method: 'get',
        url:'https://jsonplaceholder.typicode.com/todos/',//'https://jsonplaceholder.typicode.com/todos/'
    }).subscribe(
        response => {
            console.log(response);
            setThingState({ message: response.status });
        },
        error => {
            console.log(error);
            setThingState({ message: '404' });
        }
    );

}
Run Code Online (Sandbox Code Playgroud)

然后在 React 功能组件中使用 Redux 调用该函数,如下所示:

const [thingState, setThingState] = useState({ message: ''});
    function testCall(){
        thing(setThingState);
    };
Run Code Online (Sandbox Code Playgroud)

Ale*_*yne 15

您输入setIssuerCallState的是字符串。并且您不能调用字符串。

你基本上在做:

const aString = "a string"
aString() // error
Run Code Online (Sandbox Code Playgroud)

看起来这个函数的正确类型是:

function IssuerCall(setIssuerCallState: (newState: { message: string }) => void) {
   //...
}
Run Code Online (Sandbox Code Playgroud)

NowsetIssuerCallState被键入为一个函数,该函数采用单个参数,该参数是具有message属性的对象。