【问题标题】:Typescript: Typed Array connect input to output in a function打字稿:类型化数组将输入连接到函数中的输出
【发布时间】:2022-11-29 22:09:44
【问题描述】:

我正在尝试键入执行此操作的函数

  • 取一个数字类型对应的字符串,
  • 返回类型数组
  • 执行后,用户会收到有关返回的确切类型化数组的信息

但是试了半天,始终无法连接输入输出。

这是草图:

const typedArrays = {
  int8: Int8Array,
  uint8: Uint8Array,
  int16: Int16Array,
  uint16: Uint16Array,
};

interface TypedArrays<
  T extends keyof typeof typedArrays = keyof typeof typedArrays,
> {
  T: typeof typedArrays[T];
}

function doSomething<T extends keyof TypedArrays>(input:T): TypedArrays[T]{
    return new typedArrays[input]
}

Run it in the TS-playground

【问题讨论】:

    标签: typescript


    【解决方案1】:

    如果你的 TypedArrays 类型只是一个简单的 typeof typedArrays 就可以了

    type TypedArrays = typeof typedArrays;
    

    Playground

    【讨论】:

    • 那仍然行不通,我只是忘记了示例中的关键字new。
    【解决方案2】:

    主要问题是 TypedArrays 是声明为的接口

    {
      T: typeof typedArrays[T];
    }
    

    所以input被输入为"T",但是"T"不能分配给keyof typeof typedArray

    从上面的响应来看,输入更好的 TypedArrays 是正确的,但你甚至可以不使用它:

    const typedArrays = {
      int8: Int8Array,
      uint8: Uint8Array,
      int16: Int16Array,
      uint16: Uint16Array,
      int32: Int32Array,
      uint32: Uint32Array,
      uint64: BigUint64Array,
      int64: BigInt64Array,
      float32: Float32Array,
      float64: Float64Array,
    };
    
    
    function doSomething<T extends keyof typeof typedArrays>(
      input: T
    ): typeof typedArrays[T] {
      return typedArrays[input];
    }
    
    const a = doSomething("int8"); // Int8ArrayConstructor
    const b = doSomething("float32"); // Float32ArrayConstructor
    

    另外,请留意new的使用。

    以typedArrays中的int8: Int8Array为例,记住Int8Array不是类型,而是var:

    var Int8Array: Int8ArrayConstructor

    所以这会导致错误:

    function doSomething<T extends keyof TypedArray>(input: T): TypedArray[T] {
      return new typedArrays[input]; // Error
    }
    

    这是因为我们从一个应该返回 Int8ArrayConstructor 的函数返回一个真正的 Int8Array。

    为了避免这种情况,请执行以下操作:

    const typedArrays = {
      int8: Int8Array,
      uint8: Uint8Array,
      int16: Int16Array,
      uint16: Uint16Array,
      int32: Int32Array,
      uint32: Uint32Array,
      uint64: BigUint64Array,
      int64: BigInt64Array,
      float32: Float32Array,
      float64: Float64Array,
    };
    
    type TypedArray = typeof typedArrays;
    
    function doSomething<T extends keyof TypedArray>(input: T): TypedArray[T] {
      return typedArrays[input];
    }
    
    const a = new (doSomething("int8"))(); // Int8Array
    const b = doSomething("float32"); // Float32ArrayConstructor
    

    【讨论】:

    • 谢谢,但我们需要返回new typedArrays[input],这中断了。
    • @Minsky 我刚刚更新了这个例子,告诉我这是否对你有帮助
    • 它确实如此,但我正在尝试获得干净的执行,因为这是一个 API。这不会有用的。
    猜你喜欢
    • 1970-01-01
    • 2019-07-16
    • 2020-03-07
    • 2021-09-07
    • 2021-07-05
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多