TypeScript 中类型“never”上不存在属性
Property does not exist on type ‘never’ in TypeScript
never
当我们尝试访问类型值的属性时,或者当 TypeScript 在分析我们的代码时感到困惑时,就会出现错误“属性在‘never’类型上不存在” 。要解决该错误,请使用方括号访问属性,例如employee['salary']
.
下面是错误如何发生的示例。
索引.ts
type Employee = { salary: number; }; let employee: Employee | null = null; function setEmployee() { employee = { salary: 100 }; } setEmployee(); // 👉️ employee.salary is equal to 100 here // but TypeScript doesn't know if (employee == null) { console.log('employee is nullish'); } else { // ⛔️ Error: Property 'salary' does not // exist on type 'never'.ts(2339) console.log(employee.salary); }
错误的原因是
TypeScript
在分析我们的代码时感到困惑。
要解决该错误,请使用方括号而不是点符号来访问该属性。
索引.ts
type Employee = { salary: number; }; let employee: Employee | null = null; function setEmployee() { employee = { salary: 100 }; } setEmployee(); // 👉️ employee.salary is equal to 100 here // but TypeScript doesn't know if (employee == null) { console.log('employee is nullish'); } else { // ✅ Works fine now (Use bracket notation) console.log(employee['salary']); }
We used bracket notation instead of dot notation, which solved the error.
In short, do obj['myProperty']
, instead of obj.myProperty
.
Another cause of the error is declaring an empty array without assigning a type
to it.
index.ts
const obj = { years: [], }; // 👇️ never[] console.log(obj.years);
If you declare an empty array, make sure to type it explicitly to avoid any
confusing errors.
index.ts
type Example = { years: number[]; }; const obj: Example = { years: [], }; // ✅ number[] console.log(obj.years);
The three most common sources of the
never
type in TypeScript are:
- having a conditional block that is never going to run, because it is
impossible for the condition to be met - the return type of a function that throws an error
- TypeScript getting confused when analyzing our code
Conclusion #
never
当我们尝试访问类型值的属性时,或者当 TypeScript 在分析我们的代码时感到困惑时,就会出现错误“属性在‘never’类型上不存在” 。要解决该错误,请使用方括号访问属性,例如employee['salary']
.