简体   繁体   English

如何将字符串数组“变量”转换为打字稿类型?

[英]How to convert array of strings “variable” to typescript types?

I'd like to know how to convert array of string variable to type script types. 我想知道如何将字符串变量数组转换为类型脚本类型。

Note: There are two SO answers already that deal with this but strings are passed hardcoded to keep values of strings as they are. 注意:已经有两个SO答案可以解决此问题,但是字符串通过硬编码传递,以保持字符串的值不变。

Both answers pass an array in-line to keep string values in array as literals. 这两个答案都将一个内联数组传递给数组,以将字符串值作为文字保留在数组中。 But when you pass an array as a variable, it fails to work. 但是,当您将数组作为变量传递时,它将无法工作。

Passing values in-line works. 在线传递值。

编辑TypeScript-数组转换为文字-硬编码有效 在线作品

But passing values as a variable doesn't work 但是将值作为变量传递是行不通的

编辑TypeScript-数组转换为文字-不起作用 在此处输入图片说明

Question

So how do you create a type to limit a list of allowable string values in domElements as a variable to asLiterals ? 那么,你如何创建一个类型限制在可允许的字符串值的列表domElements作为一个变量来asLiterals

When an array literal is assigned to a variable, it is widened to match the typical behavior. 将数组文字分配给变量时,会将其扩展以匹配典型行为。

Because of that, the variable domElements is of type string[] instead of ('a' | 'div' | ...)[] 因此,变量domElements的类型为string[]而不是('a' | 'div' | ...)[]

The answer is in your own code. 答案在您自己的代码中。 Use a similar function as your asLiterals() to create a literal array. 使用与asLiterals()类似的函数创建文字数组。

export function literalArray<T extends KeyTypes>(...entries: T[]): T[] {
    return entries
}

You can also find this function in the type-plus library. 您也可以在type-plus库中找到此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM