【问题标题】:Contentful SDK, extending generic object Typescript type内容丰富的 SDK,扩展通用对象 Typescript 类型
【发布时间】:2021-07-31 06:24:22
【问题描述】:

我正在使用 Contentful App SDK 编写一个应用程序,但我遇到了 Typescript 类型的问题。我将参数传递给这样的对话框:

sdk.dialogs.openCurrentApp({title: "Edit Layout", parameters:{id}});

但是当我尝试访问对话框组件中的属性时,我发现当我尝试访问文档中描述的“调用”下的属性时,出现错误:“类型上不存在属性 'id' '对象'。”

const layoutId = sdk.parameters?.invocation?.id;

我尝试使用hasOwnProperty 检查该对象是否确实包含id 来强化我的代码,但它对 Typescript 输入错误没有帮助:

const layoutId = sdk.parameters?.invocation?.hasOwnProperty("id") && sdk.parameters.invocation.id;

我快速浏览了一下in the source of the SDK,发现 Parameter 确实使用了泛型对象类型。

我尝试创建一个添加了 id 的自定义类型并对其进行强制转换,但这并不完全奏效:

type ParameterInvocationWithId = {
  id: string;
} & ParametersAPI;

...

const layoutId = sdk.parameters?.invocation?.hasOwnProperty("id") && sdk.parameters.invocation.id as ParameterInvocationWithId;

解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: typescript typescript-typings contentful


    【解决方案1】:

    我想通了。我需要指定一个类型以在invocation 上显示对象的形状:

    interface InvocationParams {
      id?: string;
    }
    

    然后,我不必使用hasOwnProperty 或尝试直接访问 id,而是分两步完成,所以我将从调用对象创建一个新的 const 并将其转换为我的 params 类型,然后将 id 去掉那个对象:

    const params = sdk.dialog.parameters?.invocation as InvocationParams;
    let layoutId = params.id;
    

    【讨论】:

    • 或使用字符串访问器?喜欢sdk.dialog.parameters?.invocation['id']?
    • 试过了。也没有工作:Property 'id' does not exist on type 'Object'.
    猜你喜欢
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多