类型“未定义”不可分配给 TypeScript 中的类型

类型 ‘undefined’ 不可分配给 TypeScript 中的类型

Type ‘undefined’ is not assignable to type in TypeScript

undefined当将可能的值分配给期望不同类型的对象时,会发生“类型‘undefined’不可分配给类型”错误

要解决该错误,请在赋值前使用非空断言运算符或类型保护来验证值是否属于特定类型。

下面是错误如何发生的示例。

索引.ts
interface Employee { id: number; name: string; salary?: number; // 👈️ optional } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; // ⛔️ Error: Type 'number | undefined' is not assignable to type 'number'. // Type 'undefined' is not assignable to type 'number'.ts(2322) const salary: number = emp.salary;

该属性
界面
salary中标记为
可选Employee

这意味着该属性可以存储一个number或一个值。 undefined

salary变量的类型为 a number,因此它只希望获得一个值 a number

TypeScript 基本上是在告诉我们,该emp.salary属性的值可能undefinedsalary只需要. number

使用非空断言操作符解决错误

解决该错误的一种方法是使用
非空断言运算符

索引.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const salary: number = emp.salary!; // 👈️ non-null assertion console.log(salary); // 👉️ 100

感叹号是 TypeScript 中的非空断言运算符。

在不进行任何显式类型检查的情况下从类型中删除null和。undefined

当你使用这种方法时,你基本上告诉 TypeScript 这个值永远不会是nullor undefined

# Using a type assertion to solve the error

This approach is very similar to using a
type assertion.

index.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; const salary: number = emp.salary as number; console.log(salary); // 👉️ 100

Type assertions are used when we have information about the type of a value that
TypeScript can’t know about.

We effectively tell TypeScript that emp.salary will be a number and not to
worry about it.

# Using a union type to solve the error

You could set the type of the salary variable to be number | undefined,
which could solve the error depending on your use case.

index.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; // 👇️ types now match const salary: number | undefined = emp.salary; console.log(salary); // 👉️ 100

The type of the salary variable now matches the type of the emp.salary
property, so no error is thrown.

# Using a type guard to solve the error

An alternative approach is to use a
type guard.

index.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; const salary: number = emp.salary !== undefined ? emp.salary : 0; console.log(salary); // 👉️ 100

We used the
ternary operator to
check if the salary property is not equal to undefined.

If the property is not equal to undefined, it gets assigned to the salary
variable, otherwise we use the number 0 as a fallback.

This way we can be sure that the salary variable will always get assigned a number, even if emp.salary is undefined.

# Using the nullish coalescing operator (??) to solve the error

You could also use the
nullish coalescing operator (??)
to solve the error.

index.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; const salary: number = emp.salary ?? 0; console.log(salary); // 👉️ 100

The nullish coalescing operator (??) enables us to specify a fallback for when a
value is null or undefined.

If emp.salary is null or undefined, we set the salary variable to 0.

# Using the logical OR (||) operator to solve the error

You can also use the
logical OR (||)
operator in a similar way.

index.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; const salary: number = emp.salary || 0; console.log(salary); // 👉️ 100

The logical OR (||) operator returns the value to the right if the value to the
left is falsy.

This is different than the nullish coalescing operator (??) because nullish
coalescing only checks for null and undefined.

The logical OR (||) operator would return the value to the right if the value to
the left is any of the following: null, undefined, false, 0, "" (empty
string), NaN (not a number).

# Using an if statement to solve the error

Even a simple if statement that serves as a type guard can be used to solve
the error.

index.ts
interface Employee { id: number; name: string; salary?: number; } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; let salary = 0; // 👇️ emp.salary is number or undefined here if (emp.salary !== undefined) { // 👇️ emp.salary is number here salary = emp.salary; } console.log(salary); // 👉️ 100

We used the let keyword to initialize the salary variable to 0.

In the if statement, we check if the emp.salary property is not equal to
undefined and assign the salary variable to the corresponding value.

The “Type ‘undefined’ is not assignable to type” error occurs when a possibly
undefined value is assigned to something that expects a different type.

index.ts
interface Employee { id: number; name: string; isProgrammer?: boolean; // 👈️ optional } const emp: Employee = { id: 1, name: 'Bobby Hadz', isProgrammer: true, }; // ⛔️ Error: Type 'boolean | undefined' is not assignable to type 'boolean'. const isProgrammer: boolean = emp.isProgrammer;

The isProgrammer property has a type of boolean or undefined and the
isProgrammer variable can only ever store a boolean value.

The divergence of the types is what causes the error.

# Using a compatible type to solve the error

You can also update the type to solve the error.

index.ts
interface Employee { id: number; name: string; salary: number; // 👈️ all required } const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; const salary: number = emp.salary;

The salary property in the Employee interface is no longer
marked as optional, so the
salary variable can have a type of number without any issues.

If you don’t have access to the definition of the type, use the Required
utility type to mark all properties on the
type as required.

index.ts
interface Employee { id: number; name: string; salary?: number; // 👈️ optional property } const emp: Required<Employee> = { id: 1, name: 'Bobby Hadz', salary: 100, }; const salary: number = emp.salary;

The salary property is optional, however, we wrapped the Employee type with
the Required utility type, making all its properties required.

Now the salary property can no longer have a value of undefined.

# Conclusion

The solution to the “Type ‘undefined’ is not assignable to type” error is to
make sure that the types of the values on the left-hand and right-hand sides are
compatible.

undefined如果一个值可以,而另一个不可以,则会发生错误。

额外资源

您可以通过查看以下教程来了解有关相关主题的更多信息: