我正在使用带有nodejs的typescript来初始化数据库数据,我想声明一个全局数组变量以在函数内部使用:
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的内容放在函数变量中的seedCodesPostal中,并将其作为params传递给函数seedAddresses中。
如何将codes变量定义为CodesPostal正确性数组?
当您创建类似数组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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句