Typescript 为什么loash中的u.maxBy不返回不可定义的类型?
请参阅此代码:Typescript 为什么loash中的u.maxBy不返回不可定义的类型?,typescript,lodash,Typescript,Lodash,请参阅此代码: const studentHeights: { name: string; height: number; year: 'senior'|'junior'|'sophomore'|'freshman' }[] = []; const tallestSenior = _.chain(studentHeights) .filter((student) => student.year === 'senior') .max
const studentHeights: {
name: string;
height: number;
year: 'senior'|'junior'|'sophomore'|'freshman'
}[] = [];
const tallestSenior = _.chain(studentHeights)
.filter((student) => student.year === 'senior')
.maxBy((student) => student.height)
.value();
你希望高年级学生是什么类型的
我希望它是:{name:string;height:number,year:…}|未定义的
或可为空的
在使用typescript的VSCode中,它给了我一个不可为空的:{name:string;height:number;year:…}
。当然,这会在运行时导致bug
请注意:\uu0.maxBy(studentHeights,(student)=>student.height))
具有不可定义的正确键入
My package.json具有:
- “类型脚本”:“~4.1.5”
- “lodash”:“^4.17.21”
有什么帮助吗?只有在严格模式下运行时,未定义的代码才会出现在VSCode中,例如,如果您在tsconfig.json的编译器选项下有
strict:true
。谢谢!我还需要什么?“严格模式”似乎没有接受它。这是我的tsconfig.json:{“编译器选项”:{“模块”:“commonjs”,“noImplicitReturns”:true,“NonuUsedLocals”:true,“outDir”:“lib”,“sourceMap”:true,“strict”:true,“target”:“es2017”,“allowJs”:true,“esModuleInterop”:true,//“NonnocheckedIndexedAccess”:true},“compileOnSave”:true,“exclude”:[“lib”,“node_modules”,“ot_utils”]}