TypeScript 泛型 TypedArray : TypedArray is not assignable to T

标签 typescript

我正在学习泛型,并使用编译器解决这个问题:

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'

我在这里做错了什么?

最佳答案

没有类型断言的替代解决方案:

type TypedArray = FloatArray | IntegerArray;
type WithSubArray<T extends TypedArray> = { subarray(begin?: number, end?: number): T };

export function identityArray<T extends TypedArray>(array: WithSubArray<T>): T {
    return array.subarray(0);
}

const res1 = identityArray(new Int8Array(2)) // Int8Array 👌
const res2 = identityArray(new Float32Array(2)) // Float32Array 👌
const res3 = identityArray([1, 2, 3]) // ✖

如果将 T 声明为函数返回类型,请确保在函数体中也准确返回 T。通过使用 WithSubArray,我们可以向编译器明确表示 array.subarray 返回 T 而不是 TypedArray

TS Playground to try it out

关于TypeScript 泛型 TypedArray : TypedArray is not assignable to T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793386/

相关文章:

javascript - Node4 使用 gulp 支持 TypeScript 到 EcmaScript2015

javascript - JavaScript new Date() 使用什么时区?

javascript - JSX 错误 : Property does not exist on type 'JSX. IntrinsicElements

Angular/Firebase - Guard 在 Firebase 初始化完成之前运行

javascript - 为什么 Observable.create() 中的 setInterval() 一直在运行?

javascript - typescript 如何将新项目添加到空对象数组

typescript - 在 typescript 中提供一种对象类型

angular - Ionic - ngStyle 中来自 SASS 文件的自定义颜色

ReactJS/TypeScript - 类型 'files' 错误上不存在属性 'HTMLElement'

typescript - Visual Code for Typescript 中的 Yarn 工作区