【问题标题】:TypeScript: type or `null`TypeScript:类型或`null`
【发布时间】: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 userSessionnull 在这里?

有没有办法让函数在使用它时知道,如果用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


【解决方案1】:

TypeScript 应该能够找出它在那里是空的。我猜测发生了什么是您没有启用严格模式。

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 2022-08-23
    • 2018-01-07
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2020-05-26
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多