Jan 01, 1970
让我们从一个例子开始。假设你正在开发一个具有许多用户角色的应用程序。一个应用程序被不同的用户使用是很常见的,不是吗?确切的角色在这里并不重要,但我们假设它们是admin
、 consumer
和guest
。在 typescript 中,我们可以声明拥有这些角色的用户,如下所示:
type Admin = {} type Consumer = {} type Guest = {}
现在,让我们考虑每个用户角色具有的一组属性。通常,它们是email
、 firstName
和lastName
或类似的。但是,等等, Guest
用户可能不会有这些(毕竟他们是客人),所以我们暂时将此类型留空。
type Admin = { firstName: string lastName: string email: string } type Consumer = { firstName: string lastName: string email: string } type Guest = {}
应用程序的用户只能属于一个角色。通过类型来表示这一点的方法是使用union
类型。
type User = Admin | Consumer | Guest
type Admin = { firstName: string lastName: string email: string numberOfInvitesLeft: number // <-- added }
为了让事情变得更有趣并且更接近真实的应用,让我们添加一个专属于Consumer
类型的属性。
type Consumer = { firstName: string lastName: string email: string premium: boolean // <-- added }
const doSomethingBasedOnRole = (user: User) => { // how do you check here that user is really an admin if (user) { // ...and do something with the `numberOfInvitesLeft` property? } }
const doSomethingBasedOnRole = (user: User) => { if (user && user.numberOfInvitesLeft) { // safely access `numberOfInvitesLeft` property } }
type Admin = { firstName: string lastName: string email: string numberOfInvitesLeft: number role: "admin" // <-- added } type Consumer = { firstName: string lastName: string email: string role: "consumer" // <-- added } type Guest = { role: "guest" // <-- added }
注意我如何将特定字符串作为类型;这称为字符串文字类型。这让您现在可以使用本机 JS 语言运算符(例如switch case
、 if
、 else
来区分角色。
const user: Admin = { firstName: "John", lastName: "Smith", email: "[email protected]", numberOfInvitesLeft: 3, role: "admin", } const doSomethingBasedOnRole = (user: User) => { if (user.role === "admin") { // now typescript knows that INSIDE of this block user is of type `Admin` // now you can safely call `user.numberOfInvitesLeft` within this block } }
// ... const doSomethingBasedOnRole = (user: User) => { switch (user.role) { case "admin": { // now typescript knows that INSIDE of this block user is of type `Admin` // now you can safely call `user.numberOfInvitesLeft` within this block } case "consumer": { // do something with a `Consumer` user // if you try to call `user.numberOfInvitesLeft` here, TS compiler errors in // // "Property 'numberOfInvitesLeft' does not exist on type 'Consumer'." // } } }