我可以将字符串字面类型用于句法糖吗?

发布于 2025-02-11 16:05:15 字数 1018 浏览 1 评论 0原文

我可以使用字面类型给用户一些建议,但没有剥夺他使用自定义字符串,我尝试了:

type  fooType = string | 'suggestions-1' | 'suggestions-2';

我也尝试使用字符串类,因此它似乎有效,但对我的目的不利,

type fooType = String | 'suggestions-1' | 'suggestions-2';

我在此< a href="https://www.typescriptlang.org/play?#code/FAFwngDgpgBAyiATgSwHYHMAqlYF4YDOSa6MAPjAOQECu66URyA9qgQLQCMl5Vt9jECzbsATJQDcMAPTSYAHlz4iKDDHDRgoHPGIYAwgBsAhgQIx8CVaQrU6DJqw7dedgY5HipMuYst7SAGMTMy1taBgAUQAPYwBbCEM8GABvYBgMmAhjVChDI1MCAC5da2xoCWAAX0rApxAYVGY4e0FhYqjYhKSLVPTM7Nz8kI6AIkCaImY40Z8FJRhMAAtYAEkAEUiYABNmRuYG-gcGt2P2rh5bI7anMUpqyq0NWBj4xKhRXrTMrJy8grMJSsJABBEqNWAdTYDQA7sgQEsWu4hE4Sq9uh8vv0MoN-iMSuNJiBpjAAEY0Q6tIizWTzfDLNabQhUk7XDzOS58FnncRkikwYyGAh7OEIgUwABmiCgsECS2YyECUAeYTQICgiAlxiVMFWqHVmu1UAAYohpgAZZCkxDGRBgPo-XHDQolFQkapaWkI2WsCXIUhoGBQaIG1CCnbIQXMUjSgjQQINb26-UarVK00Wq02u0wIqQ+rqFYABTNpKScRKeoNaZNZriluttvt+FFiO5TiknrkUL9AdQQZDGrDhgjUZjjHjiZWyerRoz9azTbzUKIAsrKcN6brDezzf2SLOTiAA" rel="nofollow noreferrer">TypeScript playground

I can use the literal types to give the user some suggestions but without depriving him of using custom strings, i try this :

type  fooType = string | 'suggestions-1' | 'suggestions-2';

I also tried using the String class and so it seems to work but not good for my purpose

type fooType = String | 'suggestions-1' | 'suggestions-2';

i reproduce all in this TypeScript playground

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌伤ぢ 2025-02-18 16:05:15
type StringAndOthers<T> = T | (string & Record<never, never>);
type FooType = StringAndOthers<"suggestions-1" | "suggestions-2">;

const suggestion: FooType = 'suggestions-1';
const suggestion1: FooType = 'suggestions-2';
const suggestion3: FooType = 'suggestions-4';
type StringAndOthers<T> = T | (string & Record<never, never>);
type FooType = StringAndOthers<"suggestions-1" | "suggestions-2">;

const suggestion: FooType = 'suggestions-1';
const suggestion1: FooType = 'suggestions-2';
const suggestion3: FooType = 'suggestions-4';
甜是你 2025-02-18 16:05:15

我认为一种更好的方法是首先声明枚举

export enum abc {
    a = 'A',
    b = 'B'
   }

,然后声明您的类型:

a:abc|string 

在分配时可能使用ABC的值而不是输入字符串

I think a better approach would be to declare an enum first

export enum abc {
    a = 'A',
    b = 'B'
   }

and then declare your type:

a:abc|string 

and while assigning maybe use values from abc instead of typing strings

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文