在我看来,TypeScript不仅将typeof x === 'string'解释为简单的布尔值,而且还将其解释为某种布尔值is string类型.

请考虑以下示例:

const tryInference = function(maybeStr?: string): void {

  const isStrI          = typeof maybeStr === 'string'; // inferred type "is string"
  const isStrB: boolean = typeof maybeStr === 'string'; // explicit boolean

  console.log( isStrI && maybeStr.charAt(0) ); // <-- ok
  console.log( isStrB && maybeStr.charAt(0) ); // <-- TS18048: 'maybeStr' is possibly 'undefined'.

  const indeedStr1: string = isStrI ? maybeStr : ''; // <-- ok
  const indeedStr2: string = isStrB ? maybeStr : ''; // <-- TS2322: Type 'string | undefined' is not assignable to type 'string'

  console.log( indeedStr1, indeedStr2 );
};

我明白,在isStrI打字的情况下,知道如果是typeof maybeStr === 'string',那么maybeStr.charAt是可用的.

我想,如果是isStrB && maybeStr.charAt(0)个Typescript ,就会解释为true && maybeStr.charAt(0),与typeof maybeStr === 'string'没有关系了?(if isStrB is true, of course)

这让我想知道:

  1. 我能以某种方式显式地注释isStrI,而不 destruct maybeStrstring类型的信息吗?

  2. 我的假设正确吗?有没有人有更详细的解释?

推荐答案

这目前是不可能的.

microsoft/TypeScript#44730中实现的对control flow analysis of aliased conditions的支持不会出现在类型级别,而不是以一种可以通过编程方式操作的方式.变量的类型只有boolean;没有类型注释可以捕获它与maybeStr的关系(type predicates不是作为独立类型存在的).而且,注释该变量会 destruct 该关系:

只有当条件表达式或判别式属性访问在const变量声明中声明时,才会通过间接引用进行缩小,并且缩小的引用是const变量,readonly属性或函数体中没有赋值的参数.

Typescript相关问答推荐

如何防止TypeScript允许重新分配NTFS?

如何在方法中定义TypeScript返回类型,以根据参数化类型推断变量的存在?

为什么typescript要把这个空合并转换成三元?

如何键入函数以只接受映射到其他一些特定类型的参数类型?

匿名静态类推断组成不正确推断

在类型脚本中的泛型类上扩展的可选参数

如何解决类型T不能用于索引类型{ A:typeof A; B:typeof B;. }'

为什么不能使用$EVENT接收字符串数组?

分解对象时出现打字错误

找不到财产的标准方式?

如何按属性或数字数组汇总对象数组

接受字符串或数字的排序函数

从以下内容之一提取属性类型

TypeScrip:从嵌套的对象值创建新类型

TS不能自己推断函数返回类型

什么';是并类型A|B的点,其中B是A的子类?

Typescript 从泛型推断类型

带有过滤键的 Typescript 映射类型

Select 器数组到映射器的Typescript 泛型

错误:仅允许在‘使用服务器’文件中导出异步函数