'yield'表达式隐含地产生一个'any'类型,因为它的包含生成器缺少返回类型注释
第一个片段是我使用的代码,下面是它抛出的错误,它发生在代码中的每个“收益选择”部分,我不确定我的下一步是什么。
function* onLoadingDomainsresult() {
const pathname = yield select(getPathname);
interface Params {
hastag: string;
}
'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation. TS7057
113 |
114 | function* onLoadingDomainsresult() {
> 115 | const pathname = yield select(getPathname);
| ^
116 |
117 | interface Params {
118 | hastag: string;
回答
的文字类型select(getPathname)与您从yield. select(getPathname)是您的协程为其迭代上下文产生的值。
通过其运行上下文(通过next()调用)注入生成器的值对您从yield表达式中返回的类型很重要。
无论哪种方式,目前 Typescript 根本没有关于它将获得什么的元数据,因为您的生成器函数没有类型注释。
我猜这是 redux-saga。
典型的 Generator 函数类型注释类似于...
type WhatYouYield="foo"
type WhatYouReturn="bar"
type WhatYouAccept="baz"
function* myfun(): Generator<
WhatYouYield,
WhatYouReturn,
WhatYouAccept
> {
const myYield = "foo" //type of myYield is WhatYouYield
const myAccepted = yield myYield; //type of myAccepted is WhatYouAccept
return "baz" //type of this value is WhatYouReturn
}
...你得到的错误来自 Typescript 必须猜测WhatYouAccept类型而没有你的函数上的 Generator 类型注释。
回答
我遇到了同样的错误,我解决了。
export interface ResponseGenerator{
config?:any,
data?:any,
headers?:any,
request?:any,
status?:number,
statusText?:string
}
const response:ResponseGenerator = yield YOUR_YIELD_FUNCTION
console.log(response.data)
回答
在最近的 typescript 更新中,对生成器函数有更多类型限制。
类型 1:通过调用屈服
function* initDashboard(): any {
let response = yield call(getDashboardData);
console.log(response);
}
类型 2:没有调用的屈服
function* initDashboard() {
let response: any = yield getDashboardData;
console.log(response);
}
注意:使用any是最快的解决方案,但正确的解决方案是为响应创建类型/接口并将其用作类型。
THE END
二维码