简体   繁体   English

Typescript 声明定义字符串或任何字符串的类型

[英]Typescript declare type of defined strings or any string

I failed to find information on this elsewhere.我没有在其他地方找到这方面的信息。 I want to create a type that has both defined strings or allows any type of string to be used, but giving auto suggestion for the defined entries.我想创建一个类型,它既具有定义的字符串,也允许使用任何类型的字符串,但为定义的条目提供自动建议。

Right now if I add the // | string现在,如果我添加// | string // | string at the end, it sort of takes over, and doesn't give any auto suggestion.最后的// | string ,它有点接管,并且没有给出任何自动建议。

                                      // if I add this it stops suggestions
type DefinedLetters = 'A' | 'B' | 'C' // | string

const Letter: DefinedLetters  = '' // Should suggest A, B or C, but also allow D, E, F, etc.

I found this cool LiteralUnion type researching this for you, I think it works like a charm!我发现这个很酷LiteralUnion类型正在为你研究这个,我认为它就像一个魅力!

type LiteralUnion<T extends U, U = string> = T | (U & { });
type DefinedLetters = LiteralUnion<'A' | 'B' | 'C'>

const Letter: DefinedLetters  = "Cool!"

Why not create an enum and then in your usage, you can just specify your type as为什么不创建一个枚举,然后在您的使用中,您可以将您的类型指定为

let letter2: DefinedLetters | string;

Example 例子

enum DefinedLetters {
    A = 'A',
    B = 'B',
    C = 'C'
}

let letter1: DefinedLetters;
letter1 = DefinedLetters.A; // <- ok
letter1 = 'test'; // <-- ts error

let letter2: DefinedLetters | string;
letter2 = DefinedLetters.A; // <- ok
letter2 = 'test'; // <- ok

Not quite a type approach, but you get the same thing in this example.不完全是一种type的方法,但在这个例子中你得到了同样的东西。

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

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