1. 类型谓词
格式:类型谓词采用parameterName is Type格式,其中parameterName必须是当前函数的参数
interface Iuser {type: 'user'name: stringage: numberoccupation: string
}interface Iadmin {type: 'admin'name: stringage: numberrole: string
}export type Person = Iuser | Iadminexport const person: Person[] = [{ type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },{ type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },{ type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },{ type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' },
]// 类型谓词
const isAdmin = (person: Person): person is Iadmin => {return person.type === 'admin'
}// 类型谓词
const isUser = (person: Person): person is Iuser => {return person.type === 'user'
}export const logPerson = (person: Person) => {let test: string = ''if (isAdmin(person)) {test = person.role}if (isUser(person)) {test = person.occupation}console.log('test:', test)
}
核心代码:
const isAdmin = (person: Person): person is Iadmin => {return person.type === 'admin'
}const isUser = (person: Person): person is Iuser => {return person.type === 'user'
}
如果不使用类型收缩的话,会提示类型不存在
使用场景:在接口返回数据中,有两个不同的字段需要展示在table上时,前端做类型接收,使用interface定义两个接口,在处理数据时,判断当前的数据内容符合哪一个interface进行赋值,使用is进行类型收缩。