Time to filter the data! In order to be flexible we filter users using a number of criteria and return only those matching all of the criteria. We don't need Admins yet, we only filter Users.
Exercise:
Without duplicating type structures, modify filterUsers function definition so that we can pass only those criteria which are needed, and not the whole User information as it is required now according to typing.
exportconst isAdmin = (person: Person): person is Admin => person.type === 'admin'; exportconst isUser = (person: Person): person is User => person.type === 'user';
exportfunctionlogPerson(person: Person) { let additionalInformation = ''; if (isAdmin(person)) { additionalInformation = person.role; } if (isUser(person)) { additionalInformation = person.occupation; } console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`); }
// In case you are stuck: // https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#predefined-conditional-types
报错:
1 2 3 4 5 6 7
index.ts(101,5): error TS2345: Argument of type'{ age: number; }' is not assignable to parameter of type'User'. Type '{ age: number; }' is missing the following properties from type'User': type, name, occupation test.ts(5,5): error TS2344: Type 'false' does not satisfy the constraint 'true'. test.ts(11,5): error TS2344: Type 'false' does not satisfy the constraint 'true'. test.ts(17,5): error TS2344: Type 'false' does not satisfy the constraint 'true'. test.ts(23,5): error TS2344: Type 'false' does not satisfy the constraint 'true'. test.ts(29,5): error TS2344: Type 'false' does not satisfy the constraint 'true'.
Time to filter the data! In order to be flexible we filter users using a number of criteria and return only those matching all of the criteria. We don't need Admins yet, we only filter Users.
Exercise:
Without duplicating type structures, modify filterUsers function definition so that we can pass only those criteria which are needed, and not the whole User information as it is required now according to typing.
exportconst isAdmin = (person: Person): person is Admin => person.type === 'admin'; exportconst isUser = (person: Person): person is User => person.type === 'user';
exportfunctionlogPerson(person: Person) { let additionalInformation = ''; if (isAdmin(person)) { additionalInformation = person.role; } if (isUser(person)) { additionalInformation = person.occupation; } console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`); }
// In case you are stuck: // https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#predefined-conditional-types