假设我们有以下枚举
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
[1]。建议:打字稿中的枚举用于定义命名常量。因此,最好用名称来限定字符串文字,例如