gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:43:23 26 4
gpt4 key购买 nike

我在使用 Typescript 接口(interface)时遇到问题。我正在尝试将一个对象(缺少某些字段,例如 createdBy)转换到另一个对象,但我的转换不起作用。

我希望有人能提供帮助。

这是我拥有的接口(interface)文件:

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;
}

我正在尝试创建这个:

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

但出现以下错误:

Severity Code Description Project File Line Suppression State Error TS2352 Neither type '{ categoryId: number; lessonId: number; name: null; groupId: number; statusId: Status; toefl: boo...' nor type 'IWord' is assignable to the other. Property 'createdById' is missing in type '{ categoryId: number; lessonId: number; name: null; groupId: number; statusId: Status; toefl: boo...'. admin C:\H\admin\admin\app\routes\words.ts 102 Active

最佳答案

有一个working playground example

嗯,因为表达式的赋值word = <IWord>{ ...}确实不包含 createdByID、createdDate、modifedById、modifiedDate,我们应该简单地让它们为空

interface IWord {
...
createdById?: number;
createdDate?: string;
modifiedById?: number;
modifiedDate?: string;
}

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

实际测试 here

关于typescript - 如何在 Typescript 中将缺少字段的对象转换为另一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com