Typescript / nodejs:变量在某些位置隐式具有类型“ any”

问题描述 投票:0回答:1

我正在使用带有Node.js的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();

[我想将codesPostal的内容放在seedCodesPostal函数的codes变量内部,并将其作为params传递给函数seedAddresses。

如何将codes变量定义为CodesPostal正确性数组?

node.js arrays typescript variables
1个回答
0
投票

[当您创建一个像let arr = []的数组时,类型被推断为any[],因为Typescript不知道该数组中会有什么。

所以您只需要将该数组键入为CodePostal实例的数组:

var codesPostal: CodePostal[] = []
© www.soinside.com 2019 - 2024. All rights reserved.