typescript - TypeScript 泛型 TypedArray:TypedArray 不可分配给 T
问题描述
我正在学习泛型,并使用编译器解决这个问题:
type FloatArray = Float32Array | Float64Array;
type IntegerArray =
| Int8Array
| Uint8Array
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Uint8ClampedArray;
type TypedArray = FloatArray | IntegerArray;
export function identityArray<T extends TypedArray>(array: T): T {
return array.subarray(0);
}
// Type 'TypedArray' is not assignable to type 'T'
我在这里做错了什么?
解决方案
从文档中,只需键入 cast 您的返回行。
“相信我,我知道我在做什么。” 类型断言就像类型转换......
https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions
type FloatArray = Float32Array | Float64Array;
type IntegerArray =
| Int8Array
| Uint8Array
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Uint8ClampedArray;
type TypedArray = FloatArray | IntegerArray;
export function identityArray<T extends TypedArray>(array: T): T {
return <T>array.subarray(0);
}
推荐阅读
- html - 使用 TweenMax 缩放滚动时,文本上的图像重叠
- sql-server - 使用 Pandas 将 Pandas 数据帧附加到 Microsoft SQL 表时出现 UnicodeDecodeError
- python - requests.Response.text 显示奇数符号
- sql - SQL Server 表名姓氏
- javascript - 在 c# 中添加 html 和 javascript 函数但在 asp 页面中看起来不同并且不起作用
- three.js - 如何在three.js中实现UV坐标动画?
- r - Rmarkdown循环针织中的ggplot不起作用
- python - 使用另一个数据框选择一个数据框?
- python-3.x - 如何在 Tkinter Python Notebook 选项卡中换行文本并保持 Tkinter Notebook 选项卡的宽度不变
- apache-flink - 没有 ./bin/flink 的保存点