[英]How to restrict object fields in Typescript using Type parameter
I am using Typescript.我正在使用打字稿。 I want to create an Object like this,我想创建一个这样的对象,
const statusMessageMap = {
'ENABLE': 'This is enable',
'DISABLE': 'This is disable',
}
And I want to restrict fields of this object.我想限制这个对象的字段。 I can easily do it like this...我可以很容易地做到这一点...
interface Status = {
ENABLE: string;
DISABLE: string;
}
const statusMessageMap: Status = {
'ENABLE': 'This is enable',
'DISABLE': 'This is disable',
}
But I already have a type defined before and I want to keep it.但是我之前已经定义了一个类型,我想保留它。
type OldStatus = 'ENABLED' | 'DISABLE'
But it is not working like this...但它不是这样工作的......
//this is not working
const statusMessageMap: OldStatus = {
'ENABLE': 'This is enable',
'DISABLE': 'This is disable',
}
I don't want to keep both Status and OldStatus because, it will make me to update in two places if I want to add a new status.我不想同时保留状态和旧状态,因为如果我想添加新状态,它会让我在两个地方更新。
I want to keep my OldStatus type and want to use it to restrict type of the object.我想保留我的OldStatus类型并想用它来限制对象的类型。 How can I do it?我该怎么做? Is it possible to create a new interface extending the OldStatus type?是否可以创建一个扩展OldStatus类型的新接口?
Your message map type should be { [key in OldStatus]: string }
using OldStatus
:您的消息映射类型应该是{ [key in OldStatus]: string }
使用OldStatus
:
type OldStatus = 'ENABLE' | 'DISABLE'
const statusMessageMap: { [key in OldStatus]: string } = {
'ENABLE': 'This is enable',
'DISABLE': 'This is disable',
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.