【发布时间】:2022-01-05 17:07:45
【问题描述】:
我有一个函数接受某种类型或null。如果是null,它应该对它做一些事情,否则它应该再次返回null。
这是我尝试过的:
export const maybeMapUserSessionToUserProfile = (
userSession: UserSession | null,
): UserProfile | null => {
if (userSession) {
return mapUserSessionToUserProfile(userSession);
} else {
return userSession;
}
};
TypeScript 在 else 语句中抱怨 userSession 缺少来自 UserProfile 的属性。
Property 'id' is missing in type 'UserSession' but required in type 'UserProfile'.ts(2741)
user-profile-types.ts(10, 3): 'id' is declared here.
我怎么知道 TypeScript userSession 是 null 在这里?
有没有办法让函数在使用它时知道,如果用null 调用它,它返回null,否则返回UserProfile 类型?
编辑:
我也尝试过这样的重载:
export function maybeMapUserSessionToUserProfile(
userSession: UserSession,
): UserProfile;
export function maybeMapUserSessionToUserProfile(userSession: null): null;
export function maybeMapUserSessionToUserProfile(userSession: any): any {
if (userSession) {
return mapUserSessionToUserProfile(userSession);
}
return userSession;
}
这似乎在代码中起作用。
【问题讨论】:
-
为什么不直接返回
null? -
我相信在这种情况下重载是可以的
-
您可以添加指向TypeScript Playground 的链接并复制吗?我尝试过复制但无法复制,TypeScript 能够将第二次返回范围缩小到
null:typescriptlang.org/play?#code/… -
重载是更清洁的解决方案之一,恕我直言
-
什么是
UserSession,什么是UserProfile?你能提供一个minimal reproducible example吗?
标签: typescript typescript-types