如何在Typescript中将具有缺少字段的对象转换为另一个对象?

Sam*_*tar 5 typescript

我遇到了Typescript接口的问题.我试图将一个对象(有一些字段丢失,如createdBy)转换为另一个对象,但我的转换不起作用.

我希望有人能帮帮忙.

这是我的接口文件:

interface IWord {
    ascii?: number;
    awl570?: boolean;
    awl570Sublist?: number;
    categoryId: number;
    frequency?: number;
    groupId: number;
    lessonId: number;
    name: string;
    nawl963?: boolean;
    nawl963D?: number;
    nawl963Sfi?: number;
    nawl963U?: number;
    statusId: number;
    syllables?: string;
    toeflMcG400?: boolean;
    toeic?: boolean;
    wordForms: IWordForm[];
    wordId: number;
    createdById: number;
    createdDate: string;
    modifiedById: number;
    modifiedDate: string;
}

interface IWordForm {
    definition: string;
    posId: number;
    sampleSentences: [ISampleSentence];
    sourceId: number;
    statusId: number;
    synonyms: [ISynonym];
    wordFormId: number;
    wordId: number;
    createdById: number;
    createdDate: string;
    modifiedById: number;
    modifiedDate: string;
}
Run Code Online (Sandbox Code Playgroud)

我想创建这个:

var wos.word = <IWord>{
    categoryId: 1,
    lessonId: 1,
    name: null,
    groupId: 1,
    statusId: Status.Clean,
    toefl: true,
    wordForms: <IWordForm[]>[],
    wordId: $stateParams.wordId
}
Run Code Online (Sandbox Code Playgroud)

但是得到以下错误:

严重级代码描述项目文件行抑制状态错误TS2352都不是'{categoryId:number; lessonId:数字; name:null; groupId:number; statusId:状态; toefl:boo ...'或类型'IWord'可分配给另一个.类型'{categoryId:number;}中缺少属性'createdById'; lessonId:数字; name:null; groupId:number; statusId:状态; toefl:嘘...'.admin C:\ H\admin\admin\app\routes\words.ts 102有效

Rad*_*ler 3

有一个工作游乐场的例子

好吧,因为表达式的赋值word = <IWord>{ ...}实际上不包含createdByID、createdDate、modifedById、modifiedDate,所以我们应该简单地将它们设为可为空

interface IWord {
    ...
    createdById?: number;
    createdDate?: string;
    modifiedById?: number;
    modifiedDate?: string;
}
Run Code Online (Sandbox Code Playgroud)

换句话说 - 要么我们要求 Typescript 来检查这些是否不可为空……然后我们必须提供它们。或者它们可能会丢失,那么上述解决方案就是要走的路......

在这里进行实际测试