【发布时间】:2020-10-09 04:10:38
【问题描述】:
我正在学习打字稿,但我正在为下面的代码苦苦挣扎。
const profile = state.currentProfile;
type literalProfile = keyof Partial<Omit<Profile, 'id'>>;
const values: Record<literalProfile, string | undefined> = {
name: '',
avatar: '',
title: '',
subtitle: '',
};
Object.entries(data).forEach((entry) => {
const key = entry[0] as literalProfile;
const value = entry[1];
if (value && profile[key] !== value) {
values[key] = value;
}
});
await this.$axios.patch(`/users/profiles/${profile.id}`, values);
问题是,有没有办法像这样将值初始化为空对象?
const values: Record<literalProfile, string | undefined> = {};
因为如果我做这样的打字稿会突出显示我的错误
类型“{}”缺少类型“记录”中的以下属性':名称、标题、副标题、头像
如果我尝试这样的事情
let values: Record<literalProfile, string | undefined>;
然后打字稿说
变量“值”在被赋值之前使用。
在这一行
await this.$axios.patch(`/users/profiles/${profile.id}`, values);
所以我不知道如何解决这个问题,有什么想法吗?
【问题讨论】:
-
空对象不是该类型的有效值,因为它缺少必需的属性。也许你想要
Partial<Record<literalProfile, string>>?还是 type assertion 在初始化对象时暂时向编译器谎报对象的类型?无论哪种方式,我都希望在这里看到一个适合放入独立 IDE 的 minimal reproducible example,例如 The TypeScript Playground 来为我自己演示这个问题。一个没有 axios 的独立玩具示例会很好。 -
Playground Link 您的 Partial 解决方案效果很好,我不知道为什么我没有意识到这个解决方案。尽管如此,我想知道打字稿开发人员中更常见的解决方案是什么,您的解决方案或@wex 解决方案。还是谢谢!
标签: typescript