TypeScript覆盖现有值并强制执行字段值
我一直在试图弄清楚如何扩展接口的可选值,如果一个字段设置为特定值,那么另一个字段必须存在,我无法弄清楚这是怎么做到的 目标是:TypeScript覆盖现有值并强制执行字段值,typescript,Typescript,我一直在试图弄清楚如何扩展接口的可选值,如果一个字段设置为特定值,那么另一个字段必须存在,我无法弄清楚这是怎么做到的 目标是: 如果restricted为true,则apiData仍然是可选的 如果设置了apiData,则必须将restricted设置为true 接口路由{ 路径?:字符串 受限?:布尔值 精确?:布尔值 组件:字符串 布局?:字符串 apiData?:字符串 } 接口IRouteWithData扩展忽略{ 限制:对 apiData:FC } 类型TRoute=IRouteW
- 如果
为restricted
,则true
仍然是可选的apiData
- 如果设置了
,则必须将apiData
设置为restricted
true
接口路由{
路径?:字符串
受限?:布尔值
精确?:布尔值
组件:字符串
布局?:字符串
apiData?:字符串
}
接口IRouteWithData扩展忽略{
限制:对
apiData:FC
}
类型TRoute=IRouteWithData | IRouteConfigItem
常数routeConfig:TRoute[]=[
{
路径:'/foo',
restricted:false,//这应该是一个错误
确切地说:是的,
组件:“某物”,
apiData:“一些数据”
},
{
路径:'/bar',
受限:true,//这很好
确切地说:是的,
成分:“某物”
}
]
因此,解决方案是一种求和类型,您使用union很接近,但我们需要定义判别式,以便允许TS推断差异
// all fields which are static in all sum elements
interface IRouteBase {
path?: string
exact?: boolean
component: string
layout?: string
}
// type representing that if restricted is true - apiData needs to be set
interface IRouteWithData extends IRouteBase {
restricted: true
apiData: string
}
// type representing that if restricted is false- apiData is optional
interface IRouteMaybeData extends IRouteBase {
restricted: false
apiData?: string
}
type TRoute = IRouteWithData | IRouteMaybeData;
// example use
const mustHaveApiData: TRoute = {
component: 'component',
restricted: true, // error you need to set apiData
}
const notNeedHaveApiData: TRoute = {
component: 'component',
restricted: false, // no error, apiData is optional
}
关于使用和类型的更多信息包含在我的文章-。享受吧