参数解构和空合并的 typescript 问题

busg9geu  于 2023-05-19  发布在  TypeScript
关注(0)|答案(2)|浏览(115)

使用参数解构和null合并,typescript在可选的name属性上有问题。我不想将原始代码更改为const name = data?.resource?.name ?? [],这可能会使typescript感到高兴。我怎样才能改变类型脚本,使它能够处理空合并的参数解构?
代码

private _getName(data: Data) {
    const { name } = data.resource ?? [];

类型:

type Data = {
    fullUrl?: string,
    resource?: {
      active?: boolean,
      address?: Address[],
      birthDate?: string,
      gender?: string,
      id?: string,
      identifier?: Indentifier[],
      materialStatus?: Coding[],
      meta?: Security[],
      name?: Name[],
      resourceType?: string,
      telecom?: Telecom[],
    },
    search?: {
      extension?: Extension[],
      mode?: string,
      score: number,
    }
  };
error:
 error TS2339: Property 'name' does not exist on type '{ active?: boolean; address?: Address[]; birthDate?: string; gender?: string; id?: string; identifier?: Indentifier[]; materialStatus?: Coding[]; meta?: Security[]; name?: Name[]; resourceType?: string; telecom?: Telecom[]; } | undefined[]'.

73     const { name } = data.resource ?? []
yv5phkfx

yv5phkfx1#

这一点:

const data: { resource?: { name?: string } } = {}
const name = data?.resource?.name ?? []
console.log(name) // []

还有这个

const data: { resource?: { name?: string } } = {}
const { name } = data.resource ?? []; // type error
console.log(name) // undefined

逻辑上不相等。
data.resourceundefined时,第一个解析为数组。所以const name被赋予[]的值。
第二个期望=右侧的任何东西都具有name属性,并且该name属性的值将被分配给const name
但是数组没有name属性,所以会得到一个类型错误,在运行时将是undefined
为了使这个工作与解构,你必须确保无论是在右边这里有一个name属性。
例如:

const { name } = data.resource ?? { name: [] };

但那很傻。
我认为:

const name = data?.resource?.name ?? []

是这里最干净的解决方案。不建议使用解构赋值,除非所有可能被解构的值都支持被解构的属性。
请参见Typescript Playground。单击“Run”并查看自己的控制台输出。

inn6fuwd

inn6fuwd2#

type Data = {
  fullUrl?: string;
  resource?: {
    active?: boolean;
    address?: Address[];
    birthDate?: string;
    gender?: string;
    id?: string;
    identifier?: Indentifier[];
    materialStatus?: Coding[];
    meta?: Security[];
    name?: Name[];
    resourceType?: string;
    telecom?: Telecom[];
  } | undefined; // Make the resource property optional explicitly
  search?: {
    extension?: Extension[];
    mode?: string;
    score: number;
  };
};

相关问题