【问题标题】:Typescript/nodejs: variable implicitly has type 'any' in some locationsTypescript/nodejs:变量在某些位置隐含类型为“any”
【发布时间】:2020-09-28 22:59:33
【问题描述】:

我正在使用带有 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的内容放在codes变量里面的函数seedCodesPostal中,并把它作为参数传递到函数seedAddresses中。

如何将代码变量定义为 CodesPostal correclty 数组?

【问题讨论】:

    标签: node.js arrays typescript variables


    【解决方案1】:

    当您创建像 let arr = [] 这样的数组时,类型会被推断为 any[],因为 Typescript 不知道该数组中的内容。

    因此,您只需将该数组键入为 CodePostal 实例的数组:

    var codesPostal: CodePostal[] = []
    

    您还需要在try 块内分配codes,否则如果catch 被触发,则永远无法设置codesPostal

    通过这些编辑,您最终会在此处获得简化的代码:

    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

    【讨论】:

    • "Typescript 不知道该数组中的内容。"什么?为什么不?你是如何解决这个问题的?
    • @ahnbizcad let arr = [] 行没有关于数组成员类型的信息。我们通过let arr: CostPostal[] = [] 将数组的类型声明为CodePostal 来解决这个问题。
    • 哦,成员,而不是数组本身。所以将第一个成员设置为数组?这不是遇到递归问题吗?这不是不言而喻的,需要更多解释。
    • 递归?不,这里没有递归。这不是第一个成员,而是所有成员。这比你想象的要简单。 let arr: MyType[] = [] 说“创建一个空数组,其中所有成员(稍后添加)必须是 MyType 类型”。这里: MyType[] 是数组及其成员的类型,= [] 分配一个空数组作为值。我不知道如何解释更多细节。
    • @ahnbizcad "您将数组的第一个元素指定为数组" 这是不正确的。此答案中唯一的数组类型为CodePostal[]。这意味着数组的每个元素都必须是CodePostal 的实例。此答案中的任何代码都没有声明数组的 first 元素。仅允许在任何位置的数组成员的类型。哪一部分认为仅将第一个元素类型为数组?如果您愿意,我很乐意准确解释该部分中每个元素的作用。
    猜你喜欢
    • 2020-12-17
    • 2021-12-11
    • 1970-01-01
    • 2019-08-04
    • 2020-07-30
    • 2018-08-23
    • 1970-01-01
    • 2021-10-03
    • 2017-06-16
    相关资源
    最近更新 更多