typescript - 将类型名称转换为实际类型
问题描述
假设我们有以下枚举
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]。建议:打字稿中的枚举用于定义命名常量。所以最好通过名称来限定字符串文字,例如
enum PrimayValType {
STRING = 'string',
BOOLEAN = 'boolean',
INTEGER = 'integer',
FLOAT = 'float',
}
[2]。尝试这个:
function f(b: Buffer, t: PrimayValType=PrimayValType.STRING): number | string | boolean {
const value = b.toString('utf-8');
switch (t) {
case PrimayValType.BOOLEAN:
const isBool = /true|false/.test(value);
if (!isBool) {
throw new TypeError(`${value} is invalid for a boolean type`);
}
return /true/.test(value);
case PrimayValType.INTEGER:
case PrimayValType.FLOAT:
const isNaN = Number.isNaN(value);
if (isNaN) {
throw new TypeError(`${value} is invalid for a numeric type`);
}
return t === PrimayValType.INTEGER ? Number.parseInt(value) : Number.parseFloat(value);
default:
return value;
}
}
essertEqual(f(Buffer.from("3.14", "utf-8"), PrimayValType.FLOAT), 3.14);
assertEqual(f(Buffer.from("3.14", "utf-8"), PrimayValType.INTEGER), 3);
assertTrue(f(Buffer.from("true", "utf-8")));
修改后的答案。打字稿方式。(我没有测试过这个):
const parseBool = (value: string) => {
if (!/true|false/.test(value)) throw new TypeError(`${value} is invalid for a boolean type`);
return /true/.test(value);
};
type PrimType = "string" | "boolean" | "integer" | "float";
type Convert<T> = (str: string) => T;
type Convertors<T> = { [t in PrimType]: Convert<T> };
const convertors: Convertors<number|string|boolean> = {
"integer": parseInt,
"float": parseFloat,
"boolean": parseBool,
"string": (str) => str,
};
const f = (b: Buffer, t: PrimType) => convertors[t](b.toString('utf-8'));
推荐阅读
- python-3.x - **Kwargs 中的输出格式
- javascript - 为什么 javascript polyfill 执行会出错?
- amazon-web-services - 如何在 http 中对源进行云端 https 调用
- python - 如何通过 Python API 为 Google 电子表格中的单元格背景着色
- amazon-web-services - 无法在 Python 中连接到公共 RDS 实例
- html - 单击 URL 并将其下载为 HTML,而不是访问它
- angular - Angular : 发出 post 请求后,如何触发 get 请求并使用修改后的值更新组件?
- javascript - 如何使用 javascript 变量使用 cssText 更改 div 的高度
- php - 使用 ajax 和 codeigniter 的电子邮件 ID 可用性检查
- c# - 我是否使这种方法过于复杂以确定类型是否实现接口?