TypeScript中普通目录和Nest项目之间find方法的类型推断差异

webghufk  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(133)

我写了两个类似的代码,一个在普通目录中,另一个在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 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,而在第二个代码中,result的类型是Car而不是Car| undefined是什么意思

ztigrdn8

ztigrdn81#

造成差异的原因是Typescript配置之间的差异。我怀疑在“普通目录”中,你启用了严格的编译器选项,这保证了更严格的类型检查。strict编译器选项启用此系列的所有选项:

alwaysStrict
strictNullChecks
strictBindCallApply
strictFunctionTypes
strictPropertyInitialization
noImplicitAny
noImplicitThis
useUnknownInCatchVariables

您可以启用所有这些选项,也可以启用真正导致这种差异的选项,即strictNullChecks
文件:
strictNullChecksfalse时,nullundefined实际上被语言忽略。这可能导致运行时出现意外错误。当strictNullCheckstrue时,nullundefined有自己不同的类型,如果你试图在需要具体值的地方使用它们,你会得到一个类型错误。例如,对于这段TypeScript代码,users.find不能保证它真的能找到用户,但你可以编写代码,就好像它能找到用户一样:

declare const loggedInUsername: string;
 
const users = [
  { name: "Oby", age: 12 },
  { name: "Heera", age: 32 },
];
 
const loggedInUser = users.find((u) => u.name === loggedInUsername);
console.log(loggedInUser.age);

strictNullChecks设置为true将引发一个错误,即您在尝试使用loggedInUser之前没有保证它存在。

相关问题