547n00n
547n00n

Reputation: 1536

Typescript/nodejs: variable implicitly has type 'any' in some locations

I'm using typescript with nodejs to init DB data, I want to declare a global array variable to use inside functions :

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();

I want to put the content of codesPostal in the function seedCodesPostal inside codes variable and the pass it as params in the function seedAddresses.

how to define the codes variable as array of CodesPostal correclty ?

Upvotes: 16

Views: 57658

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187004

When you create an array like let arr = [] the type is inferred to be any[], because Typescript doesn't know what will be in that array.

So you just need to type that array as an array of CodePostal instances:

var codesPostal: CodePostal[] = []

You also need to assign codes within the try block, or else codesPostal could never be set if the catch is triggered.

With those edits you end up with the simplified code here:

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);
    }
}

Playground

Upvotes: 21

Related Questions