【发布时间】:2020-08-08 12:39:13
【问题描述】:
在我的 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' });
}
);
}
但是,如果我将类型设置为任何,那么我没有问题。如下面的代码所示。我仍在研究 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' });
}
);
}
然后在 React 功能组件中调用此函数,Redux 如下所示:
const [thingState, setThingState] = useState({ message: ''});
function testCall(){
thing(setThingState);
};
【问题讨论】:
-
您尝试将其称为此处的函数:
setIssuerCallState({ message: response.status });并在几行之后再次调用它。显然 TypeScript 不允许在string上这样做。如果它不是string,为什么要尝试将其注释为string? -
你希望
const a = "string"; a()做什么? -
@Thomas -- 谢谢,我明白我现在做错了什么。我猜我只是需要第二双眼睛。
-
我没有不尊重的意思!我只是想通过你得到的错误来说明打字稿试图告诉你的内容。我们曾经都是初学者。您提出了一个非常明确的问题,我很乐意为您提供帮助:)
标签: javascript reactjs typescript redux