下面是一些示例代码。 TypeScript将validStudents
的类型推断为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 'ValidStudent[]'. // Type 'Student' is not assignable to type 'ValidStudent'. // Type 'Student' is not assignable to type '{ isValid: true; }'. // Types of property 'isValid' are incompatible. // Type 'boolean' is not assignable to type 'true'.ts(2345) foo(validStudents);
可以通过添加类型断言来使此代码正常工作:
const validStudents = students.filter(student => student.isValid) as ValidStudent[];
...但感觉有些不客气。 (或者也许我比自己更信任编译器!)
是否有更好的方法来处理此问题?
下面是一些示例代码。 TypeScript推断validStudents的类型为Students []。对于所有阅读该代码的人来说,显而易见的是,由于所有无效记录均被过滤掉,validStudents ...
这里发生了一些事情。