Typescript 函数可以 return Promise<any> 和 Promise<Bar> 一样吗?
Typescript function can return Promise<any> as Promise<Bar>?
我正在为 fetch-api 创建一个类型安全的包装器,我注意到打字稿编译器将其归类为完全有效的代码:
function foo(response: Response): Promise<Bar> { //response received from a fetch() call
const json: Promise<any> = response.json();
return json; //Promise<any> can be returned as Promise<Bar>?
}
为什么可以直接return一个Promise<any>
作为Promise<Bar>
?这不应该需要某种类型的断言吗?
永远避免any
。 any
根据定义可以分配给任何东西,也可以从任何东西分配,而无需任何类型断言。当用作泛型类型参数时,结果类型(ex Promise<any>
)通常可以分配给该位置上具有任何其他类型参数的任何其他实例(ex Promise<Bar>
)。
自从 3.0 typescript 引入 unknown
(阅读 了解更多信息)它与 any 相似,你可以为它分配任何东西,如果没有类型断言,它不能分配给任何其他东西。所以这是一个错误:
let u: Promise<unknown>
let n: Promise<number> = u; // error
您也可以查看 tslint 规则 no-unsafe-any
和 no-any
以防止在项目中使用 any
,具体取决于您希望禁止 any
的程度],就像我一开始说的那样,我会完全禁止它,并在绝对必要的少数情况下添加例外。
如果某物可以是 any
,它也可以是 Bar
。如果您查看 Basic Types 的 Typescript 文档,它会说(强调我的)
Any
We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:
这意味着 any
类型完全忽略编译时类型检查。
我正在为 fetch-api 创建一个类型安全的包装器,我注意到打字稿编译器将其归类为完全有效的代码:
function foo(response: Response): Promise<Bar> { //response received from a fetch() call
const json: Promise<any> = response.json();
return json; //Promise<any> can be returned as Promise<Bar>?
}
为什么可以直接return一个Promise<any>
作为Promise<Bar>
?这不应该需要某种类型的断言吗?
永远避免any
。 any
根据定义可以分配给任何东西,也可以从任何东西分配,而无需任何类型断言。当用作泛型类型参数时,结果类型(ex Promise<any>
)通常可以分配给该位置上具有任何其他类型参数的任何其他实例(ex Promise<Bar>
)。
自从 3.0 typescript 引入 unknown
(阅读
let u: Promise<unknown>
let n: Promise<number> = u; // error
您也可以查看 tslint 规则 no-unsafe-any
和 no-any
以防止在项目中使用 any
,具体取决于您希望禁止 any
的程度],就像我一开始说的那样,我会完全禁止它,并在绝对必要的少数情况下添加例外。
如果某物可以是 any
,它也可以是 Bar
。如果您查看 Basic Types 的 Typescript 文档,它会说(强调我的)
Any
We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:
这意味着 any
类型完全忽略编译时类型检查。