假设我有一个像这样的歧视联盟:
type Route = HomeRoute | ProfileRoute | BlogRoute;
type HomeRoute = {
route: '/home'
}
type ProfileRoute = {
route: '/profile/:userId',
params: {
userId: string;
}
}
type BlogRoute = {
route: '/blog/:teamId',
params: {
teamId: string;
}
}
我有一个对Route
个对象进行操作的函数,如果它们有参数,则有一些可选逻辑:
function processRoute(route: Route) {
if ('params' in route) {
const { params } = route; // <-- this errors
}
}
在没有添加params
注释的情况下检查any
似乎不是一种方式(我可以看到)...
function paramsInRoute(route: any): route is { params: {[key: string]: string} } {
return ('params' in route);
}
function processRoute(route: Route) {
if ('params' in route) {
const { params } = route; // <-- this errors
}
if (paramsInRoute(route)) {
const { params } = route; // <-- this typechecks
}
}
有没有办法在没有强制转换的情况下执行上述操作(在paramsInRoute
参数中)?
答案 0 :(得分:3)
我个人很乐意使用你拥有的护卫员:
function paramsInRoute(route: any): route is { params: {[key: string]: string} } {
return ('params' in route);
}
因为TypeScript肯定会将传入的Route
对象缩小为ProfileRoute
| BlogRoute
if (paramsInRoute(route)) {
const notHomeRouteAnymore: ProfileRoute | BlogRoute = route; // no error
}
但如果你担心有人这样做:
const notRoute = "This is not a route";
if (paramsInRoute(notRoute)) { notRoute.params.oops = 'what' };
然后你可以这样做:
function paramsInRoute(route: Route): route is Route & { params: {[key: string]: string} } {
return ('params' in route);
}
执行相同的缩小但防止错误调用:
paramsInRoute(notRoute); // error
希望有所帮助;祝你好运!