首页 > 解决方案 > 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'

我在这里做错了什么?

标签: typescript

解决方案


从文档中,只需键入 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);
}

推荐阅读