下面是一些示例代码。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)