将字符串数组转换为TypeScript类型 [英] Convert array of strings to TypeScript type

查看:234
本文介绍了将字符串数组转换为TypeScript类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个字符串数组:

Say I have an array of strings:

const s = ['foo', 'rolo', 'zoombaz'];

所以我会得到:

type v = {
   foo: string,
   rolo: string,  
   zoombaz: string
}

奖金:理想情况下,我希望将它们映射到骆驼箱,所以如果我有:

bonus: Ideally I am looking to map them to camel-case, so if I had:

const s = ['foo', 'rolo', 'zoom-baz'];

我会得到:

type v = {
   foo: string,
   rolo: string,  
   zoomBaz: string
}

在某些情况下,我想告诉它使用布尔值而不是字符串.这是用于命令行解析器的.

in some cases, I would want to tell it to use boolean instead of string. This is for a command line parser.

推荐答案

首先,您需要获取TypeScript才能将数组的元素类型推断为字符串文字类型的并集,而不是扩展为string.编译器支持的标准技巧是通过一个标识函数来运行数组,该函数可以推断受string约束的元素类型:

First you'll need to get TypeScript to infer the element type of the array as a union of string literal types instead of widening to string. The standard trick supported by the compiler to do this is to run the array through an identity function that infers an element type constrained by string:

function asLiterals<T extends string>(arr: T[]): T[] { return arr; }
const s = asLiterals(['foo', 'rolo', 'zoombaz']);

现在您可以定义:

type v = {[K in (typeof s)[number]]: string};

TypeScript不会在类型系统中进行任何字符串操作,例如骆驼式的外壳.但是,您可以首先在所需类型的框内定义名称,然后在运行时将其转换为其他任何框.

TypeScript won't do any string manipulation such as camel-casing in the type system. However, you could initially define the names in the casing you want for types and then convert to whatever other casing at runtime.

这篇关于将字符串数组转换为TypeScript类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆