简体   繁体   English

让TS抱怨与非空字段的空比较?

[英]Getting TS to complain about null comparison to a non-nullable field?

Is there a way to get TS to complain about this? 有没有办法让TS对此进行投诉? I have strictNullChecks on 我有strictNullChecks

const foo: string = 'asdf';

if (foo !== null) {
    console.log(foo);
}

If, for instance, I change that condition to: 例如,如果我将条件更改为:

if (foo !== 42) {

I get: 我得到:

This condition will always return 'true' since the types 'string' and 'number' have no overlap. 由于类型“字符串”和“数字”没有重叠,因此此条件将始终返回“ true”。

You can't cause an error with === because TS has special carve-outs that make comparison with null / undefined always allowed. 您不能使用===引起错误,因为TS具有特殊的分割,可以始终与null / undefined进行比较。

If you're willing to use a helper function, you can use a conditional type to ensure that null is a possible value of the tested expression: 如果您愿意使用辅助函数,则可以使用条件类型来确保null是被测试表达式的可能值:

function isNull<T>(x: T): null extends T ? boolean: void {
   return (x === null) as any;
}

// Error
declare const a: string;
if (isNull(a)) { }

// OK
declare const b: string | null;
if (isNull(b)) { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在执行更改时会收到“无法为不可为空的字段返回 null”错误? - Why am I getting a “Cannot return null for non-nullable field” error when doing a mutation? 无法为 GraphQL 查询中的不可空字段返回 null - Cannot return null for non-nullable field in a GraphQL query GraphQL 查询返回错误“不能为不可为空的字段返回空值” - GraphQL query returns error "Cannot return null for non-nullable field" Prisma API返回关系但客户端返回“不能为非可空字段返回null”。 - Prisma API returns relation but client returns “cannot return null for non-nullable field..” 为什么这会抛出“不能为不可为空的字段 Query.hello 返回 null。”? - Why does this throw "Cannot return null for non-nullable field Query.hello."? GraphQL 错误:无法为不可为空的字段 Mutation.deleteComment 返回 null - GraphQL Error: Cannot return null for non-nullable field Mutation.deleteComment graphql 解析器返回 无法从 nodejs 中的异步 function 为非空字段返回 null - graphql resolver return Cannot return null for non-nullable field from asynchronous function in nodejs 为什么 graphql 返回“不能返回 null of non-nullable field mutation.createAccnt” - why is graphql returning “cannot return null of non-nullable field mutation.createAccnt” 在 graphql 中更新/编辑用户数据(不能为不可空字段 Mutation.updateUser 返回 null) - Updating/editing user data in graphql(Cannot return null for non-nullable field Mutation.updateUser) 阿波罗服务器+续集错误不可为空的字段 - apollo server + sequelize error non-nullable field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM