将类型名称转换为实际类型

问题描述 投票:0回答:1

假设我们有以下枚举

enum PrimayValType {
  "string",
  "boolean",
  "integer",
  "float"
}

现在我想编写一个函数,该函数输入Buffer和类型为PrimaryValType的参数,并根据PrimaryValType转换缓冲区。如何在Typescript中编写这样的函数?

function f(b: Buffer, t: PrimayValType): ??? {
    // converts b to a literal based on t
}

const b = Buffer.from('test', 'utf-8');
f(b, PrimayValType.string) // should be of type string
typescript typescript2.0 typescript1.8 typescript1.5
1个回答
0
投票

[1]。建议:打字稿中的枚举用于定义命名常量。因此,最好用名称来限定字符串文字,例如

© www.soinside.com 2019 - 2024. All rights reserved.