TypeScript按可选键排序对象数组遇TS2532错误的解决方法
修复TS2532错误的三种方案
针对你遇到的因可选属性触发的TS2532(对象可能为undefined)错误,结合你“不会传入可选键调用函数”的前提,提供以下修复方案:
方案1:从类型层面限制参数为必填属性(最安全)
通过TypeScript类型工具提取Test中的必填属性,让函数参数仅接受必填键,从根源上避免可选属性的问题:
export type Test = { adam: string; eve?: string; }; // 提取类型中的必填属性键 type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T]; export type Container = { test: Array<Test>; }; const testContainer = {} as Container; export function sortTest(prop: RequiredKeys<Test>) { testContainer.test.sort((a, b) => { return a[prop] > b[prop] ? -1 : b[prop] > a[prop] ? 1 : 0; }); }
该方案会在编译阶段阻止传入可选键eve,完全符合你的调用约定,同时彻底消除TS错误。
方案2:使用类型断言
若不想修改参数类型,可在排序逻辑中用类型断言明确告知TypeScript当前属性值为字符串:
export type Test = { adam: string; eve?: string; }; export type Container = { test: Array<Test>; }; const testContainer = {} as Container; export function sortTest(prop: keyof Test) { testContainer.test.sort((a, b) => { // 因你保证不会传入可选键,此断言安全 const valA = a[prop] as string; const valB = b[prop] as string; return valA > valB ? -1 : valB > valA ? 1 : 0; }); }
方案3:使用非空断言操作符
利用TypeScript的非空断言!,直接标记属性值不会为undefined:
export type Test = { adam: string; eve?: string; }; export type Container = { test: Array<Test>; }; const testContainer = {} as Container; export function sortTest(prop: keyof Test) { testContainer.test.sort((a, b) => { // 非空断言:告知TS属性值一定存在 return a[prop]! > b[prop]! ? -1 : b[prop]! > a[prop]! ? 1 : 0; }); }
内容的提问来源于stack exchange,提问作者Olli
相关产品推荐
相关产品推荐

