我已经创建了这些类型
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'.
答案 0 :(得分:0)
一个快速的答案是在tsconfig.json中禁用strictNullChecks
(或命令行,或用于配置打字稿的任何内容),以便您可以将null
分配给几乎所有内容,甚至无需将类型设置为null
。就像所有定义都隐式包含| null
一样。
如果您仍然需要启用strictNullChecks
,则类型必须匹配。 string
变量只能接收string
类型的相同方式,hostel
必须与Maybe<Hostel>
(即Hostel | null
)具有相同的类型,因此:
export type Maybe<T> = T | null;
hostels: Array<Maybe<Hostel>>;
hostel: Hostel | null;
if (hostels && hostels.length > 0) {
hostel = hostels[0];
}