gpt4 book ai didi

javascript - 如何使用 Typescript 创建一个包含对象的字段的新对象?

转载 作者:行者123 更新时间:2023-11-28 18:36:46 25 4
gpt4 key购买 nike

我有以下 Typescript 接口(interface)文件,我正在尝试创建一个简单的 Word 类型的最小对象,其中包含一个 WordForm 对象:

interface IWord {
categoryId: number;
createdBy: number;
createdDate: any;
groupId: number;
ielts: boolean;
lessonId: number;
modifiedBy: number;
modifiedDate: any;
toefl: boolean;
toeic: boolean;
wordForms: IWordForm[];
wordId: string;
}

interface IWordForm {
createdBy: number;
createdDate: any;
definition: string;
modifiedBy: number;
modifiedDate: any;
posId: number;
primary: boolean;
sample1: string;
sample2: string;
sample3: string;
sample4: string;
sample5: string;
synoym: string;
wordFormId: string;
wordId: string;
}

这工作正常:

            wos.word = <IWord>{
categoryId: 1,
lessonId: 1,
groupId: 1,
toefl: true
}

但这给了我一个错误:

            wos.word = <IWord>{
categoryId: 1,
lessonId: 1,
groupId: 1,
toefl: true,
wordForm: <IWordForm>{
posId: 1
}
}

Severity Code Description Project File Line Suppression State Error TS2352 Neither type '{ categoryId: number; lessonId: number; groupId: number; toefl: boolean; wordForm: IWordForm; }' nor type 'IWord' is assignable to the other. Property 'createdBy' is missing in type '{ categoryId: number; lessonId: number; groupId: number; toefl: boolean; wordForm: IWordForm; }'. admin C:\H\admin\admin\app\routes\words.ts 76 Active

Severity Code Description Project File Line Suppression State Error Build: Neither type '{ categoryId: number; lessonId: number; groupId: number; toefl: boolean; wordForm: IWordForm; }' nor type 'IWord' is assignable to the other. admin C:\H\admin\admin\app\routes\words.ts 76

有人可以帮忙告诉我如何创建一个包含单词形式的单词对象吗?请注意,我知道我的作业中缺少很多参数,但通过强制转换,我认为这应该仍然有效。

最佳答案

在您的具体情况下,问题是界面有一个 wordForms 属性,该属性采用 IWordForm 列表,但您提供了一个 wordForm (单数)属性,具有单个单词形式,而不是列表。如果您重命名它并将表单包装在列表中,它应该可以工作:

wos.word = <IWord> {
categoryId: 1,
lessonId: 1,
groupId: 1,
toefl: true,
wordForms: [{
posId: 1
}]
}

更一般地说,这不是选 Angular 的工作原理。在这种情况下, Actor 阵容并没有什么帮助。当您转换某些内容时,您 promise 它具有您提供的类型,如果您可能是对的,那就没问题(例如,将 string|number 转换为 number),但如果 TypeScript 知道你肯定是错的(将字符串转换为数字),则它不会允许这样做,前提是你可能是对的。

如果您通常需要避免这种情况,您可以通过首先强制转换为 any 来强制 TypeScript 接受您的正确性,如下所示。没有充分理由不要这样做! (测试中的 stub /模拟是我所知道的为数不多的好理由之一):

wos.word = <IWord> <any> {
categoryId: 1,
lessonId: 1,
groupId: 1,
toefl: true,
wordForm: <IWordForm>{
posId: 1
}
}

关于javascript - 如何使用 Typescript 创建一个包含对象的字段的新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36937674/

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