我有一个看起来像这样的界面
export interface IAppSection {
key: string;
order: number;
header: string;
content: string;
modifiedAt: string;
modifiedByEmployeeId: number;
change: 'added' | 'removed' | 'updated' | 'none';
}
Run Code Online (Sandbox Code Playgroud)
我想做的是在存储与该接口相关的对象时使用change默认值none。
我已经尝试过了,change: 'added' | 'removed' | 'updated' | 'none' = 'none'但这不起作用。
我敢肯定,我在这里做错了什么,对于我如何实现这一目标,我将不胜感激。
你不能用接口来做到这一点。接口在运行时完全擦除,不会影响运行时行为;这是设计使然。您可以改为创建一个类并为该字段分配一个默认值,或者您可以创建一个将分配默认值的函数。
我们甚至可以构造一个函数来帮助我们使用默认值创建这样的函数:
interface IAppSection {
key: string;
order: number;
header: string;
content: string;
modifiedAt: string;
modifiedByEmployeeId: number;
change: 'added' | 'removed' | 'updated' | 'none';
}
function withDefaults<T>() {
return function <TDefaults extends Partial<T>>(defs: TDefaults) {
return function (p: Pick<T, Exclude<keyof T, keyof TDefaults>> & Partial<TDefaults>) :T {
let result: any = p;
for (let k of Object.keys(defs)) {
result[k] = result[k] || defs[k];
}
return result;
}
}
}
const appSection = withDefaults<IAppSection>()({
change: 'none'
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10698 次 |
| 最近记录: |