Extract And Exclude Union Members
Narrow unions at the type level with Extract, Exclude, and NonNullable, mirroring each type operation with the matching array filter at runtime.
Code
// Extract / Exclude / NonNullable: 筛选、剔除联合类型的成员
type Route = 'home' | 'admin' | 'settings' | 'login' | 'signup';
type PublicRoute = Extract<Route, 'login' | 'signup'>;
type ProtectedRoute = Exclude<Route, PublicRoute>;
const navRoutes: Route[] = ['home', 'login', 'admin', 'signup', 'settings'];
const isPublic = (route: Route): route is PublicRoute =>
route === 'login' || route === 'signup';
const publicRoutes = navRoutes.filter(isPublic);
const protectedRoutes = navRoutes.filter((r): r is ProtectedRoute => !isPublic(r));
console.log(publicRoutes.join(','), '|', protectedRoutes.join(','));
// NonNullable:从联合中剔除 null 与 undefined
type Id = number | null | undefined;
type PresentId = NonNullable<Id>;
const ids: Id[] = [1, null, 3, undefined];
const present = ids.filter((v): v is PresentId => v != null);
console.log(present.join(','));
const first: ProtectedRoute = 'admin'; // 放开 'login' 即编译错误
console.log('menu:', first);Output
Captured from a sandboxed run of this snippet in the build pipeline.
login,signup | home,admin,settings
1,3
menu: adminHow it works
The working surface is the function isPublic — everything else is wiring.
Applying it
The primary signature is const isPublic = (route: Route)
The demo output is labeled (menu:), so every printed line traces back to the operation that produced it.
Statements that matter
const protectedRoutes = navRoutes.filter((r): r is ProtectedRoute => !isPublic(r));
const present = ids.filter((v): v is PresentId => v != null);
Interactive Tools for This Topic
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `isPublic` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.