属性 使用 Promises 在“{}”类型上不存在
Property does not exists on type '{}' using Promises
我正在访问从已解决的承诺返回的对象的 属性。
return new Promise((resolve) => {
// Get result
resolve(result)
}).then(r => console.log(r.id))
Typescript 编译代码并且代码有效,但我的 IDE 抱怨 r.id
[ts] Property 'id' does not exist on type '{}'.
'TypeScript'处理这个问题的方法是什么? This question seems to have the same issue but I cannot understand the given solutions. 谈论使用接口,但我不确定如何将其应用于 Promise
的 then()
函数
Typescript 无法通过使用 resolve
来判断 Promise
的结果类型,您需要将结果类型显式指定为 Promise
的泛型参数:
new Promise<{ id: string }>((resolve) => {
// Get result
resolve(result)
}).then(r => console.log(r.id))
您可以将 { id: string }
替换为任何类型,因为 bonus typescript 将检查是否使用正确的结果类型调用了 resolve
。
编辑
我假设有一些更复杂的代码需要使用 Promise
构造函数而不是 // Get result
。如果您已经知道结果,您可以只使用 Promse.resolve(result)
它将正确键入承诺,正如@BenjaminGruenbaum 在评论中指出的那样
我正在访问从已解决的承诺返回的对象的 属性。
return new Promise((resolve) => {
// Get result
resolve(result)
}).then(r => console.log(r.id))
Typescript 编译代码并且代码有效,但我的 IDE 抱怨 r.id
[ts] Property 'id' does not exist on type '{}'.
'TypeScript'处理这个问题的方法是什么? This question seems to have the same issue but I cannot understand the given solutions. Promise
then()
函数
Typescript 无法通过使用 resolve
来判断 Promise
的结果类型,您需要将结果类型显式指定为 Promise
的泛型参数:
new Promise<{ id: string }>((resolve) => {
// Get result
resolve(result)
}).then(r => console.log(r.id))
您可以将 { id: string }
替换为任何类型,因为 bonus typescript 将检查是否使用正确的结果类型调用了 resolve
。
编辑
我假设有一些更复杂的代码需要使用 Promise
构造函数而不是 // Get result
。如果您已经知道结果,您可以只使用 Promse.resolve(result)
它将正确键入承诺,正如@BenjaminGruenbaum 在评论中指出的那样