简体   繁体   English

Typescript 无法推断构造函数返回类型

[英]Typescript can not infer constructor return type


type ArrayBufferViewConstructor<T> = new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number) => T;

function asView<V, C extends ArrayBufferViewConstructor<V>>(
    TypedArray: C,
    v: BufferSource,
    byteOffset?: number,
    byteLength?: number,
  ): V{
    return undefined as V
  }

let a = asView(Uint8Array, new Uint32Array)
a
D.TS TS
 declare type ArrayBufferViewConstructor<T> = new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number) => T; declare function asView<V, C extends ArrayBufferViewConstructor<V>>(TypedArray: C, v: BufferSource, byteOffset?: number, byteLength?: number): V; declare let a: unknown;

I expected a is Uint8Array , but got unknown我预计aUint8Array ,但unknown

Compiler Options 编译器选项
{ "compilerOptions": { "strict": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictPropertyInitialization": true, "strictBindCallApply": true, "noImplicitThis": true, "noImplicitReturns": true, "alwaysStrict": true, "esModuleInterop": true, "declaration": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "ES2017", "jsx": "react", "module": "ESNext", "moduleResolution": "node" } }

Playground Link: Provided游乐场链接: 提供

How do define the type make return type is Uint8Array ?如何定义类型使返回类型为Uint8Array

Making use of the built-in InstanceType , there is no need for the generic parameter V .利用内置的InstanceType ,不需要通用参数V We just need to use it here, in the return type of the function:我们只需要在这里使用它,在 function 的返回类型中:

): InstanceType<C> {

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM