javascript - 我一直发现自己在使用 TypeScript 时遇到同样的错误。当我需要返回执行后已知的类型时,我该怎么办?
问题描述
例如:这会引发错误
export const toArray = <T>(potentialArr: T): [T] =>
kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];
错误
TS2322: Type 'T | [T]' is not assignable to type '[T]'. Type 'T' is not assignable to type '[T]'.
但我知道这总是会返回一个数组,我做错了什么?TypeScript 忽略了我告诉它它将返回一个数组的事实是没有意义的。
无论我如何在逻辑上撰写此内容,我似乎都无法对打字进行推理。
export const toArray = <T>(potentialArr: T | [T]): T | [T] =>
kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];
这应该工作不?
但我得到错误
TS2322: Type 'T | [T | [T]]' is not assignable to type 'T | [T]'. Type '[T | [T]]' is not assignable to type 'T | [T]'. Type '[T | [T]]' is not assignable to type '[T]'. Type 'T | [T]' is not assignable to type 'T'. 'T | [T]' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'. Type '[T]' is not assignable to type 'T'. '[T]' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
然后如果我这样做:
export const toArray = <T>(potentialArr: T): T | [T] =>
kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];
它可以正常工作,但是从此函数派生的每个值都输入为 x | [x] 这不是真的,因为从这个函数派生的每个值总是 [x]
与此相同:
export const toArray = <T>(potentialArr: T) =>
kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];
解决方案
这是一个对我来说没有错误的解决方案:
function foo<T>(input: [T] | T): [T] {
return Array.isArray(input) ? input : [input];
}
如果kindOf
不是打字稿理解的东西,您仍然可以以这种方式使用它:
function isArray(input: any): input is any[] {
return kindOf(input) === 'array';
}
但是您实际上只是重新实现了内置的Array.isArray
,这是更正确的方法。
推荐阅读
- wordpress - WordPress 帖子计数错误
- microsoft-graph-api - 有没有办法将 One Drive(即 xlsx 格式)中的工作表恢复为本地 .ODS 格式?
- python - Python在将JsonL转换为CSV文件时为CSV文件插入标题
- list - (wx)Maxima:关闭科学计数法
- python - Flask-SocketIO 未在服务器上接收事件
- java - 如何在片段中插入共享首选项
- python - 切换路由时有时会注销 - Heroku Flask_SQLAlchemy
- c++ - 头文件和源文件错误
- docker - 为什么`docker-compose.yml`中指定的ARGS在`Dockerfile`中可用于`docker compose run`而不是`docker compose build`?
- c# - 为什么 webapi 的 post 方法在从邮递员调用时接收类型接口为 null 的参数?