【问题标题】:How to narrow a type using typeof keyword?如何使用 typeof 关键字缩小类型?
【发布时间】:2019-06-17 07:18:24
【问题描述】:
interface Students {
    [key:string]: (Student | undefined);
}

interface Student {
    age: string;
}

function something (students:Students, student_name:string) {
    let student:Student;

    if (typeof students[student_name] !== 'undefined')
        student = students[student_name]; // Type 'Student | undefined' is not assignable to type 'Student'.
    else
        return;
}

我经常遇到这种情况。当然,我可以使用作为学生。但是,我想知道是否有更好的方法。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    通常,TypeScript 将使用control-flow analysis 来自动缩小值的类型,一旦你检查了它。但是您遇到的问题是这种缩小不会发生在括号样式的属性访问中(请参阅microsoft/TypeScript#10530),例如students[student_name]。它适用于 literal 索引类型(请参阅 microsoft/TypeScript#26424),例如 students["Alice"],相当于 students.Alice... 但要使其与 string 一起使用显然也会降低编译器性能很多。

    这里的解决方法是只执行一次索引访问,并将结果分配给一个新变量。然后,当您检查该变量时,控制流分析应根据需要缩小:

    function something(students: Students, student_name: string) {      
      let student: Student;      
      const maybeStudent = students[student_name]; // Student | undefined
      if (typeof maybeStudent !== 'undefined')
        student = maybeStudent; // okay, maybeStudent narrowed to Student in check
      else
        return;
    }
    

    Playground link to code

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2022-01-22
      相关资源
      最近更新 更多