繁体   English   中英

将打字稿别名转换为具有联合类型的接口

[英]Converting typescript alias into interface with union type

如何将此type alias转换为接口?

type Color = 'RED' | 'GREEN' | 'BLACK';
const color: Color = 'RED';

我的直觉是要使用,但这是错误的。

interface Color {
  [item: 'RED' | 'GREEN' | 'BLACK']: string;
}
const color: Color = 'RED'

我想做的是用接口替换类型。 因此,基本上只能为该接口类型的变量分配以下值之一:“ RED”,“ GREEN”或“ BLUE”

类型别名和interafecs不可互换。

有时,如果可以将类型别名解析为简单的对象类型,则两者在使用它们时的作用非常接近。

如果类型别名是联合,则不能将其更改为接口

您可以转换的联合类型为使用接口 通用接口

这是一个类型联合:


type Color = 'RED' | 'GREEN' | 'BLACK';
const color: Color = 'RED';

这是转换为接口:


interface Color<Label1="RED", Label2="GREEN", Label3="BLACK"> {
    name: Label1 | Label2 | Label3
}

const color: Color = { name: "RED" } // ok, static checked 


尽管根据您的特定用例,您是否愿意只使用一个enum 像这样:


enum Color {
    RED = 'RED',
    GREEN = 'GREEN',
    BLACK = 'BLACK'
}

const color: Color = Color.RED // ok, static checked ---> color = 'RED'


暂无
暂无

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

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