我正在处理一个遗留的数据集,并且正在尝试在typescript中对一些有意义的类型进行建模。在这个例子中,假设我有一个员工课程中关于工作经验的数据:
EMPLOY | START | END
'my first employ' | 20180901 | 20181001
'my last employ' | 20180901 | null如果END为null,则表示它是实际的雇员。因为我有几条关于这个领域概念的业务规则,所以我想用类型对它进行建模。下面是我的代码:
interface ActualExperience {
actual: true,
employ: string,
start: Date,
end: undefined // <-- no end!
}
interface PreviousExperience {
actual: false,
employ: string,
start: Date,
end: Date // <-- end has a value!
}
type Experience = ActualExperience | PreviousExperience到目前一切尚好。然后我想使用我的类型:
// this is OK
const previous: PreviousExperience = {
actual: false,
employ: 'my first employ',
start: new Date(),
end: new Date()
}
// ERROR!
const actual: ActualExperience = {
actual: true,
employ: 'my last employ',
start: new Date()
}Typescript要求我为了映射到ActualEmploy显式定义end: undefined
// this is OK now!
const actual: ActualExperience = {
actual: true,
employ: 'my last employ',
start: new Date(),
end: undefined
}这对我来说是非常不切实际的,因为我必须显式地将一个未定义的值添加到记录中,这只会让我的编译器感到高兴。
我如何设计这样的类型模型?
发布于 2019-01-22 18:06:50
将您的接口声明为:
interface ActualExperience {
actual: true,
employ: string,
start: Date
}如果在以后的代码调用actual.end中,javascript将返回undefined,则无需像在接口"ActualExperience“中那样定义它。
发布于 2019-01-22 18:09:50
有两种方法可以做到这一点。
首先,如果没有特别需要在ActualExperience中显式地使用end: undefined,那么可以直接删除它。
其次,根据您正在尝试做的事情,使用额外的接口可能更有意义:
interface BaseExperience {
actual: boolean,
employ: string,
start: Date,
end?: Date
}然后,您可以指定当前接口实现BaseExperience
interface ActualExperience extends BaseExperience {
actual: true,
employ: string,
start: Date
}
interface PreviousExperience extends BaseExperience {
actual: false,
employ: string,
start: Date,
end: Date
}最后,您可以直接使用BaseExperience
const someExperience: BaseExperience = {
actual: true,
employ: 'my last employ',
start: new Date()
}以你想要的方式使用你的ActualExperience
const actual: ActualExperience = {
actual: true,
employ: 'my last employ',
start: new Date()
}https://stackoverflow.com/questions/54305397
复制相似问题