首页 > 解决方案 > 将类型名称转换为实际类型

问题描述

假设我们有以下枚举

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

标签: typescripttypescript2.0typescript1.8typescript1.5

解决方案


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

推荐阅读