相关疑难解决方法(0)

为什么 TypeScript 不能从过滤后的数组中推断类型?

下面是一些示例代码。TypeScript 推断validStudentsas的类型Students[]。任何阅读代码的人都应该很清楚,因为所有无效记录都被过滤掉了,validStudents所以可以安全地将ValidStudents[].

interface Student {
    name: string;
    isValid: boolean;
}
type ValidStudent = Student & { isValid: true };

const students: Student[] = [
    {
        name: 'Jane Doe',
        isValid: true,
    },
    {
        name: "Robert'); DROP TABLE Students;--",
        isValid: false,
    }
];

const validStudents = students.filter(student => student.isValid);

function foo(students: ValidStudent[]) {
    console.log(students);
}

// the next line throws compile-time errors:
// Argument of type 'Student[]' is not assignable to parameter of type …
Run Code Online (Sandbox Code Playgroud)

type-inference typescript

7
推荐指数
1
解决办法
1099
查看次数

标签 统计

type-inference ×1

typescript ×1