我刚刚安装了TypeScript 3.4,并注意到我的某些Mongoose中间件功能不再是有效的TypeScript。
TypeScript输出
model.ts:19:8 - error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
19 this.modified = new Date();
架构定义
Schema.pre("save", next => {
this.modified = new Date();
next();
});
TSLint建议先将this
强制转换为unknown
,然后将其强制转换为模型类型。
Schema.pre("update", next => {
(<Model>(<unknown>this)).modified = new Date();
next();
});
这似乎可行,但并非整洁或易于理解。
如何更好地解决此问题?我不想禁用TS规则。
答案 0 :(得分:3)
嗨,最好的方法显示在相关的git问题中: https://github.com/Automattic/mongoose/issues/5046
如此处所述:
因此,这与Typescript无关。问题是你 使用粗箭头语法定义猫鼬方法和钩子。不要做 那。如果使用粗箭头功能定义预保存钩子,它将 没有词汇范围,也不能绑定到给定的上下文。
因此将next =>
替换为function(next) {}
,它应该可以正常工作
答案 1 :(得分:0)
用train_test_split
代替random
似乎可以得到正确的值。但是如果您尝试访问# First shuffle the list randomly
files = os.listdir("C:/.../my_folder")
random.shuffle(files)
# Then just slice
ratio = int(len(files)/5) # 20%
test_set = files[:ratio]
val_set = files[ratio:1.5*ratio] #30%
=>
要解决此问题,您可以使用function(next) {}
和this.username
之类的getter和setter方法,也可以在下面进行操作
Error: TS2339: Property 'username' does not exist on type 'Document'.