node.js - Typescript/nodejs:变量在某些位置隐含类型为“any”
问题描述
我正在使用带有 nodejs 的 typescript 来初始化 DB 数据,我想声明一个全局数组变量以在函数内部使用:
export { };
import {Address,CodePostal} from 'api/models';
const faker = require('faker')
const _ = require('lodash')
const quantity = 20
var codes
async function setup() {
const adminUser1 = new User(ADMIN_USER_1);
await adminUser1.save();
await seedCodesPostal()
}
async function checkNewDB() {
const adminUser1 = await User.findOne({ email: ADMIN_USER_1.email });
if (!adminUser1) {
console.log('- New DB detected ===> Initializing Dev Data...');
await setup();
} else {
console.log('- Skip InitData');
}
}
const seedCodesPostal = async () => {
try {
var codesPostal = []
for (let i = 0; i < quantity; i++) {
codesPostal.push(
new CodePostal({
codePostal: faker.address.zipCode("####")
})
)
}
codesPostal.forEach(async code => {
await code.save()
})
} catch (err) {
console.log(err);
}
codes = codesPostal ***// here is the error : variable codes has implicitly type 'any' in some locations where its type cannot be determined ***//
}
const seedAddresses = async (codes: any) => {
try {
const addresses = []
for (let i = 0; i < quantity; i++) {
addresses.push(
new Address({
street: faker.address.streetName(),
city: faker.address.city(),
number: faker.random.number(),
codePostal: _.sample(codes),
country: faker.address.country(),
longitude: faker.address.longitude(),
latitude: faker.address.latitude(),
})
)
}
} catch (error) {
}
}
checkNewDB();
我想将codePostal的内容放在codes变量内的函数seedCodesPostal中,并将其作为参数传递给函数seedAddresses。
如何将代码变量定义为 CodesPostal correclty 数组?
解决方案
当您创建一个数组时let arr = []
,类型被推断为any[]
,因为 Typescript 不知道该数组中的内容。
因此,您只需将该数组键入为CodePostal
实例数组:
var codesPostal: CodePostal[] = []
您还需要codes
在try
块内分配,否则如果触发codesPostal
则永远无法设置。catch
通过这些编辑,您最终得到了简化的代码:
const quantity = 20
// Added type here
var codes: CodePostal[] = []
class CodePostal {
async save() { }
}
const seedCodesPostal = async () => {
try {
// Added type here.
var codesPostal: CodePostal[] = []
for (let i = 0; i < quantity; i++) {
codesPostal.push(
new CodePostal()
)
}
codesPostal.forEach(async code => {
await code.save()
})
// Moved assignment inside try block
codes = codesPostal
} catch (err) {
console.log(err);
}
}
推荐阅读
- ajax - Ajax 到数据库安全吗?
- c# - 将两个字典的值转换为 DateTime
- r - 关于在 R 中重新编码分类变量的问题
- python - Scrapy,Twisted 严重错误:ImportError: DLL load failed
- jdbc - 可以很好地处理经常空闲的连接的 JDBC 连接池库?
- php - 如何在 JSON 中查找值并取消设置?
- r - 从R中的文件路径中提取TOP目录
- c# - C# 通过 linq 将通用 xml 展平为 csv
- c# - 如何编写 SQL 查询以返回数据库中每年的 TODAY'S DATE(月和日)的所有“历史记录”?
- php - 为什么replace没有保存?