[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'));