作者:COCO歧 | 来源:互联网 | 2023-02-04 13:40
我试图让编译器检查一个承诺的类型,但我得到一个奇怪的行为.以下是return
我尝试的4种不同选项:
interface MyResponse {
foo: number,
data: T,
}
const g: () => Promise> = async () => {
// This behavior is fine, the compiler complains, as expected:
// ERROR: Type 'string' is not assignable to type 'number'.
return {
foo: 1,
data: 'wrong type'
}
// Both foo and data are missing, but I get no error. I don't get why
return {}
// data is missing, but still no error
return {
foo: 1
}
// Now the compiler complains about `data` being missing
// ERROR: Property 'data' is missing in type '{ foo: number; bar: string; }'.
return {
foo: 1,
bar: 'this fails'
}
}
值得注意的是,如果我不使用Promise
(也不async
),那么我会得到预期的错误.
知道为什么会这样吗?
[编辑]:这与应该用typescript 2.4修复的打字稿错误有关(参见关于github的讨论)
@ nitzan-tomer的答案仍然是一个很好的解决方法,直到下一个版本.
1> Nitzan Tomer..:
当您稍微更改函数的签名时,似乎解决了此问题:
const g = async (): Promise> => {
...
}
使用原始签名会发生这种情况:
const g1 = async () => {
return {}
}
const g2: () => Promise> = g1
g1
is 的类型() => Promise<{}>
和编译器认为可以将此类型分配给() => Promise>
.
只有当返回值的结构与结构冲突时才会抱怨MyResponse
.
编辑
从版本2.4开始修复此问题.
原始问题:使用异步函数和通用类型时出现奇怪的检查错误.
相关:Promise.then奇怪的通用参数推断.
修复:协调检查回调参数.