代码之家  ›  专栏  ›  技术社区  ›  Fred Hors

如何使用此生成的typescript代码正确键入“let skills”?

  •  1
  • Fred Hors  · 技术社区  · 3 年前

    我正在使用typescript来描述一个变量,但我遇到了一个奇怪的问题:

    import type { PlayerByIdQuery } from "generated/queries";
    
    let skills: PlayerByIdQuery["playerById"]["skills"];
    

    错误为:

    Property 'skills' does not exist on type '{ __typename?: "Player" | undefined; id: string; number: string; skills?: { ...; }[] | ... 1 more ....'.ts(2339)
    

    类型为:

    export type PlayerByIdQuery = {
      __typename?: "Query";
      playerById?: {
        __typename?: "Player";
        id: string;
        number: string;
        skills?: Array<{
          __typename?: "PlayerSkill";
          description: string;
          id: string;
          playerId: string;
        }> | null;
      } | null;
    };
    

    如果我将类型更改为(注意两者都缺失 | null )以下为:

    export type PlayerByIdQuery = {
      __typename?: "Query";
      playerById: {
        __typename?: "Player";
        id: string;
        number: string;
        skills?: Array<{
          __typename?: "PlayerSkill";
          description: string;
          id: string;
          playerId: string;
        }>;
      };
    };
    

    我做错了什么?

    如何正确键入 let skills ?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Alex Wayne    3 年前

    问题是 playerById 是可选的(可能是 undefined )或者 null

    null['skills'] 无效,这意味着:

    type A = { skills: string[] } | null
    type B = A['skills'] // also not valid
    

    因此,您需要明确删除 未定义的 无效的 从类型开始,然后再进行深入研究。

    幸运的是,typescript附带了一个实用程序类型,用于 NonNullable<T>

    type A = { skills: string[] } | null
    type B = NonNullable<A>['skills'] // now works fine
    

    所以现在只需将其应用于您自己的类型,如下所示:

    let skills: NonNullable<PlayerByIdQuery["playerById"]>["skills"] = [
      {
        __typename: 'PlayerSkill',
        description: 'Fancy punch',
        id: 'abc123',
        playerId: 'def456'
      }
    ]
    

    See playground

    推荐文章