type GraphQLType =
| GraphQLInt
| GraphQLList<any>
| GraphQLNonNull<any>;
interface GraphQLInt {
int: number
}
interface GraphQLList<T> {
x: string
}
interface GraphQLNonNull<T> {
x: string
}
declare function isInt(type: GraphQLType): type is GraphQLInt;
declare function isList(type: GraphQLType): type is GraphQLList<any>;
declare function isNonNull(type: GraphQLType): type is GraphQLNonNull<any>;
function doIt(t: GraphQLType) {
if (isInt(t)) {
return t.int
}
if (isList(t)) {
// t: GraphQLList<any> | GraphQLNonNull<any>
return t.x
}
// t: never
if (isNonNull(t)) {
return t.x
}
}
上面的示例在 isNonNull() 块中导致错误,因为它确定 t 的类型为 never。在 isList() 块中,t 具有 GraphQLList 和 GraphQLNonNull 两种类型。这两种类型在结构上是相同的。这是此处和此处描述的相同问题还是实际上是一个错误?
它应该起作用的原因是因为 isList() 是 GraphQLList 而不是 GraphQLNonNull 的类型保护,并且在运行时它将为 List 返回 true,为 NonNull 返回 false,但 typescript 似乎并不代表相同的想法。