TypeScript中普通目录与Nest项目find方法的类型推断差异
为什么两段相似TypeScript代码中
result的类型不一致? 我编写了两段相似的TypeScript代码,一段位于普通目录,另一段在Nest项目中:
普通目录下的代码
//Normal Directory class Car{ id: number; } let Carslist: Car[] = [{id:1}, {id:2}, {id:3}, {id:4}, {id:5}]; function getbyID(arg:number){ let result = Carslist.find((elem) =>elem.id == arg); console.log(result) }
Nest项目中的代码
//Nest Project import { HttpException, Injectable } from '@nestjs/common'; import { Car } from './car'; @Injectable() export class CarService { Carslist: Car[] = []; getbyID(arg:number){ let result = this.Carslist.find((elem) =>elem.id == arg); console.log(result); } }
在第一段代码中,result的类型为Car | undefined,但在第二段Nest项目的代码中,result的类型却为Car而非Car | undefined,请问这是什么原因?
原因分析
两段代码的类型差异核心在于TypeScript配置中的strictNullChecks选项:
普通目录下的TypeScript配置(如
tsconfig.json)大概率开启了strictNullChecks: true。当该选项开启时,TypeScript会严格处理null和undefined类型,Array.find()方法若未找到匹配项会返回undefined,因此result的类型被推断为Car | undefined。NestJS项目的
tsconfig.json可能默认未开启strictNullChecks(或被手动修改为false)。此时TypeScript会自动忽略undefined类型,将result的类型直接推断为Car,即便find()可能返回undefined。
除此之外,也需确认两段代码中Car类型的定义是否一致,但从给出的代码片段来看,配置差异是最可能的原因。
内容的提问来源于stack exchange,提问作者Sarang Dutta
相关产品推荐
相关产品推荐

