类型'null'不能分配给类型'XXX'

问题描述 投票:0回答:1

我已经创建了这些类型

export type Maybe<T> = T | null;
hostels: Array<Maybe<Hostel>>;
hostel: Hostel;


if (hostels && hostels.length > 0) {
            hostel = hostels[0];
}

但是我有这个编译错误:

Type 'null' is not assignable to type 'Hostel'.
javascript node.js typescript
1个回答
0
投票

一个快速的答案是在tsconfig.json(或命令行,或用于配置打字稿的任何东西)中禁用strictNullChecks,因此即使无需将输入类型设置为[ C0]。就像所有定义都隐式包含null一样。

如果仍然需要启用null,则类型必须匹配。 | null类型只能接收strictNullChecks类型的方式相同,string必须与string的类型相同,即hostel,因此:

Maybe<Hostel>
© www.soinside.com 2019 - 2024. All rights reserved.