类型保护不适用于通用参数? [英] Type guard don't work with generic params?

查看:40
本文介绍了类型保护不适用于通用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

type SomeType = {
    foo: string;
} | undefined;

function someFn<TParams extends SomeType>(params1: SomeType, params2: TParams): void {
  if (params1) {
    Object.entries(params1);
  }
  if (params2) {
    Object.entries(params2); // here is an error
  }
}

TypeScript 无法确定 params2 不包含 undefined.对此是否有合理的解释,还是 TypeScript 中的错误?

TypeScript cannot determine that params2 does not contain undefined. Is there a logical explanation for this, or is it a mistake in TypeScript?

在线演示这里

推荐答案

This is an open issue in typescript (https://github.com/microsoft/TypeScript/issues/4742).自动类型保护和泛型并不总是一起工作.作为一种可能的解决方法,您可以手动定义此类型保护:

This is an open issue in typescript (https://github.com/microsoft/TypeScript/issues/4742). Automatic type guards and generics don't always work together. As a possible work around you could define this type guard manually:

type SomeType = {
    foo: string;
} | undefined;

function isDefined<T> (v: T): v is Exclude<T, undefined> {
  return v !== undefined
}

function someFn<TParams extends SomeType>(params1: SomeType, params2: TParams): void {
  if (params1) {
    Object.entries(params1);
  }
  if (isDefined(params2)) {
    Object.entries(params2);
  }
}

这篇关于类型保护不适用于通用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆