Typescript:如何获得接口可接受/定义的值列表?
如何获得接口可接受/定义的值列表 示例I将本地州定义为:Typescript:如何获得接口可接受/定义的值列表?,typescript,Typescript,如何获得接口可接受/定义的值列表 示例I将本地州定义为: interface LocalState { justifyContent: 'space-between' | 'center' | 'flex-start' | 'flex-end' | 'space-around' | 'space-evenly'; } 我想得到一个包含 ['space-between', 'center', 'flex-start', 'flex-end', 'space-around', 'space
interface LocalState {
justifyContent: 'space-between' | 'center' | 'flex-start' | 'flex-end' | 'space-around' | 'space-evenly';
}
我想得到一个包含
['space-between', 'center', 'flex-start', 'flex-end', 'space-around', 'space-evenly']
是否可以从TS类型系统中提取此信息?(或者在传输到Javascript时将其剥离)
如果可能的话怎么办?因为类型/接口是与类型相关的概念,而JS是一种非常动态类型化的语言。。。这不是个好主意。 也就是说,我们可以创建一个包含所有必需属性的
enum
,只需使用JSObject.values()
即可从中获取数组。当然,我们可以使用枚举作为类型
enum LocalState {
spaceBetween = 'space-between',
center = 'center',
flexStart = 'flex-start'
}
const localStateArr: LocalState[] = Object.values(LocalState);
console.log(localStateArr) // logs ["space-between", "center", "flex-start"]
部分示例:
这就是创建和使用简单界面的方法
interface LocalStateWithEnum {
string : LocalState;
}
// or even more strict:
interface LocalStateWithEnumStrict {
'justifyContent' : LocalState;
}
const a: LocalStateWithEnumStrict = {
justifyContent : LocalState.center
}
完整示例:const contentPositions=[“间距”、“中心”、“弹性起点”、“弹性终点”、“周围间距”、“均匀间距”];
接口本地状态{
证明内容:内容位置的类型[数量];
}
接口在生成的JavaScript中没有占用空间,因此不适合预期用途。改为使用类。关于文档中接口的更多信息-使用(“空格-中间”|“中心”|…
)而不是枚举将是一种更直接的方法。在枚举中很容易错误地使用值与键。这是一本有趣的读物-
const contentPositions = <const>["space-between", "center", "flex-start", "flex-end", "space-around", "space-evenly"];
interface LocalState {
justifyContent: typeof contentPositions[number];
}