如何使用typeof关键字缩小类型?

时间:2019-01-23 16:29:01

标签: typescript

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;
}

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

2 个答案:

答案 0 :(得分:2)

通常,一旦您检查了值,TypeScript就会使用control-flow analysis自动缩小值的类型。但是您遇到的问题是this narrowing does not happen with bracket-style property accessestry: subprocess.call(["/path/to/dir/analyze","--arg1",a,"--arg2",b]) except: subprocess.call(["/path/to/dir/analyze","--arg1",b,"--arg2",a]) 一样。它是recently addressed for literal index types(例如students[student_name],等效于students["Alice"]),但是使其与students.Alice一起使用显然会大大降低编译器性能。

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

string

希望有所帮助;祝你好运!

答案 1 :(得分:1)