简体   繁体   English

Typescript/nodejs:变量在某些位置隐含类型为“any”

[英]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:我正在使用 typescript 和 nodejs 来初始化数据库数据,我想声明一个全局数组变量以在函数内部使用:

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.我想将代码邮政的内容放在代码变量中的 function 种子代码邮政中,并将其作为参数传递给 function 种子地址。

how to define the codes variable as array of CodesPostal correclty?如何将代码变量定义为 CodesPostal correclty 数组?

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.当您创建像let arr = []这样的数组时,类型被推断为any[] ,因为 Typescript 不知道该数组中的内容。

So you just need to type that array as an array of CodePostal instances:因此,您只需将该数组键入为CodePostal实例的数组:

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.您还需要在try块中分配codes ,否则如果触发了catch ,则永远无法设置codesPostal

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 操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node + TypeScript:“this”隐式具有类型“any” - Node + TypeScript: 'this' implicitly has type 'any' 参数 'req' 隐含地具有 'any' 类型 - Typescript - Parameter 'req' implicitly has an 'any' type - Typescript RN打字稿中参数隐式具有任何类型 - Parameter implicitly has any type in RN typescript TypeScript NodeJS 应用程序错误:元素隐式具有“任何”类型,因为类型“typeof globalThis”没有索引签名.ts(7017) - TypeScript NodeJS application Error: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) TypeScript - 元素隐式具有“任何”类型 [...] 在类型上未找到具有“字符串”类型参数的索引签名 - TypeScript - Element implicitly has an 'any' type [...] No index signature with a parameter of type 'string' was found on type TypeScript警告=&gt; TS7017:对象类型的索引签名隐式具有任何类型 - TypeScript warning => TS7017: Index signature of object type implicitly has any type 参数 'info' 隐式具有 'any' 类型 - Parameter 'info' implicitly has an 'any' type 获取本地 JSON 数据:该元素隐式具有类型“any” - Get local JSON data: The element has a type "any" implicitly 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}” - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{} 'this' 隐含类型为 'any' 因为它没有类型 annotation.ts(2683) - 'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM