我已经创建了这些类型
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'.
一个快速的答案是在tsconfig.json(或命令行,或用于配置打字稿的任何东西)中禁用strictNullChecks
,因此即使无需将输入类型设置为[ C0]。就像所有定义都隐式包含null
一样。
如果仍然需要启用null
,则类型必须匹配。 | null
类型只能接收strictNullChecks
类型的方式相同,string
必须与string
的类型相同,即hostel
,因此:
Maybe<Hostel>