字符串属性上的 TypeScript 接口默认值



我有一个看起来像这样的界面

export interface IAppSection {
key: string;
order: number;
header: string;
content: string;
modifiedAt: string;
modifiedByEmployeeId: number;
change: 'added' | 'removed' | 'updated' | 'none';
}

我想做的是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'
})

您不能在接口中设置默认值,只能在实现中设置。

但默认情况下,它们是未定义的,这基本上很好。

对于"真正的"实现,您的字符串联合看起来不错。

另请参阅: 打字稿接口默认值

另一种处理方法是将所有IAppSection值标记为必需,然后使用工厂方法创建IAppSection对象,在工厂方法中您可以确保满足所有不变量,并为每个实例的可选参数分配默认值

const createAppSection = (
key: string,
order: number,
header: string,
content: string,
modifiedAt: string,
modifiedByEmployeeId: number,
change?: 'added' | 'removed' | 'updated' | 'none';
) : IAppSection => {
// perform invariants validations 
if(!key){
throw Error('key required');
}
return {
key, order, content, modifiedAt, modifiedByEmployeeId,
change: change || 'none'
}
}

我遇到了同样的问题,并找到了以下解决方案

由于接口仅在编译时工作,因此它们不能用于设置运行时默认值。 幸运的是,TypeScript 为此提供了一种解决方法。 通过使用 TypeScript pick 实用程序类型,我们可以从接口中选择属性并为它们提供默认值。

interface IPerson {
firstName: string;
lastName: string;
role: string;
}
type DefaultValues = Pick<IPerson, 'role'>;
const defaultPersonValues: DefaultValues = {
role: 'guest'
}

最后:

const newPerson: PersonWithDefaultsOptional = {
firstName: 'Tim',
lastName: 'Mousk'
};
const person: IPerson = {
...defaultPersonValues,
...newPerson
}

有关更多信息,请阅读本文: 如何设置 TypeScript 接口默认值?

最新更新