打字稿:typeof 的输出是否有字符串文字类型的联合?

时间:2021-03-01 16:39:22

标签: typescript

我知道 typeof 的输出类型是一个字符串。

在打字稿中有这种模式,称为"Union of string literal types"

export type Fruit = 'banana' | 'apple' | 'orange';

问:任何库中是否存在可导入的字符串文字类型联合,以确保字段只能是 typeof 运算符的可能输出?

示例伪代码:

import {JSType} from '@somelib/types'; // <--- what I want, this is a bogus type/lib

export class SomeClass {
    data: any;
    type: JSType;
    constructor (params) {
        this.data = params.data;
        this.type = typeof params.data;
    }
    render = () => {
        switch(this.type){
            case 'boolean':
                // return checkbox html component
            // more type cases
            default:
                // return input html component
        }
    }
}

我可以手动创建我需要的类型,但我更愿意让比我更聪明的人来处理类型的维护,如果 JS/TS 曾经添加除“字符串”之外的其他类型,我更愿意为未来提供证明 | '数' | '功能' | '对象' | '未定义'。

另外,如果我需要添加自定义类型,那么我可以只用 extend the existing type 来包含我需要的字符串。

编辑 #1: 更新了术语。感谢 jcalz

1 个答案:

答案 0 :(得分:2)

必须有更好的方法来做到这一点,因为这些定义已经存在于某处。但是我们可以通过以下方式以非常迂回的方式访问联合:

  • 创建类型为 any 的变量
  • 对该变量调用 JS typeof,这将返回所有可能类型的联合
  • 创建使用 TS typeof 将该联合作为类型访问的打字稿类型。
const x: any = "";

const t = typeof x;

type TypeofTypes = typeof t;

这会产生

type TypeofTypes = "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

Typescript Playground Link