如何为类型创建文字值?
Posted
技术标签:
【中文标题】如何为类型创建文字值?【英文标题】:How to create a literal value for a type? 【发布时间】:2018-12-10 11:37:11 【问题描述】:从https://***.com/a/51132333/936293继续,为什么以下不起作用?
type MemberModel = mongoose.Document &
familyName: string,
otherNames: string,
email: string
function f(m: MemberModel):void
f1( email: "abc@gmail.com" );
最后一行导致编译器错误:
类型参数 ' email: string; ' 不可分配给“MemberModel”类型的参数。输入'电子邮件:字符串; ' 不可分配给类型“文档”。 ' email: string; 类型中缺少属性 'increment' '。
email: "abc@gmail.com"
不符合MemberModel
类型指定的形状?
在这种情况下,如何将合适的文字传递给f
? (此时我想避免将MemberModel
更改为类,因为我从模板继承了此代码。)
【问题讨论】:
为什么会是一个有效的MemberModel
?它甚至没有你在类型中内联定义的所有道具,更不用说mongoose.Document
需要的任何东西了。
【参考方案1】:
简单的答案是不,对象字面量不符合该类型。它不符合,因为对象文字只有 email
字段。该类型需要满足 mongoose.Document
有很多方法(包括 increment
这是你得到的错误)以及你指定的所有字段都是必需的,所以即使我们只考虑那部分它仍然会不起作用,因为它缺少字段 familyName
和 otherNames
。
您可以接收此类型的 Partial<T>
,它允许我们指定该类型字段的任何子集:
type MemberModel = mongoose.Document &
familyName: string,
otherNames: string,
email: string
function f(m: Partial<MemberModel>): void
f( email: "abc@gmail.com" );
例如,更正确的方法可能是阅读mongoose
如何定义架构和类here。您可能正在寻找类似的东西:
type MemberModel = mongoose.Document &
familyName: string,
otherNames: string,
email: string
var memberModelSchema = new mongoose.Schema(
familyName: String,
otherNames: String,
email: String
);
var MemberModel = mongoose.model<MemberModel>('MemberModel', memberModelSchema);
function f(m: MemberModel): void
f(new MemberModel( email: "abc@gmail.com" ));
【讨论】:
以上是关于如何为类型创建文字值?的主要内容,如果未能解决你的问题,请参考以下文章
如何为文件类型创建所有文件关联(友好的应用程序名称和可执行文件)的 C# 列表