简体   繁体   English

内容丰富的 SDK,扩展通用 object Typescript 类型

[英]Contentful SDK, extending generic object Typescript type

I am writing an app using the Contentful App SDK, but I'm running into an issue with Typescript typings.我正在使用 Contentful App SDK 编写一个应用程序,但我遇到了 Typescript 类型的问题。 I'm passing a parameter to a dialog like so:我将参数传递给一个对话框,如下所示:

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

But when I try to access the property in the dialog component I find that when I try to access the attribute under "invocations" as described in the documentation, I get an error: "Property 'id' does not exist on type 'Object'."但是当我尝试访问对话框组件中的属性时,我发现当我尝试访问文档中描述的“调用”下的属性时,我收到一个错误:“属性'id'不存在于类型'对象' 。”

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

I tried using hasOwnProperty to check that the object indeed contains id to harden my code, but it does not help with the Typescript typing error:我尝试使用hasOwnProperty来检查 object 确实包含id来强化我的代码,但它对 Typescript 输入错误没有帮助:

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

I had a quick look in the source of the SDK and found that the Parameter indeed uses a generic object type.我快速查看了 SDK 的源代码,发现 Parameter 确实使用了通用的 object 类型。

I tried making a custom type with id added and casting to that, but that does not quite work:我尝试制作一个添加了 id 的自定义类型并对其进行强制转换,但这并不完全奏效:

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

...

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

What would be the best way to deal with this?处理这个问题的最佳方法是什么?

I figured it out.我想到了。 I needed to specify a type to show the shape of the object on invocation :我需要指定一个类型以在invocation时显示 object 的形状:

interface InvocationParams {
  id?: string;
}

Then, instead of using hasOwnProperty or trying to access id directly I had to do it in two steps, so I would create a new const from the invocation object and cast it to my params type and then pluck the id off that object:然后,不是使用hasOwnProperty或尝试直接访问 id,我必须分两步完成,所以我将从调用 object 创建一个新的 const 并将其转换为我的参数类型,然后从 object 中提取 id:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM