如何在运行时检查类型是否具有索引签名(How to check if type has index signature at runtime)

编程入门 行业动态 更新时间:2024-10-10 06:14:53
如何在运行时检查类型是否具有索引签名(How to check if type has index signature at runtime)

我不确定这是否有意义,因为许多类型都是JavaScript中的对象,但是我们在这里:

我想实现一个类型保护 ,它检查类型是否实现索引签名 。 怎么会那样做?

换句话说,如何实现这个功能的主体:

function hasIndexSignature(o: complexunioninterface | { [index: string]: string }): o is { [index: string]: string } { return /* Help? */; }

考虑到许多类型都是对象,这是正确的实现:

function hasIndexSignature(o: complexunioninterface | { [index: string]: string }): o is { [index: string]: string } { return typeof o === "object"; }

一种方法是为complexunioninterface实现一个类型保护,并且只是否定它,但是我感兴趣的是如果为索引签名实现类型保护将是有意义的,如果可能的话。

I'm not sure if this makes any sense, because many types are objects in JavaScript, but here we go:

I want to implement a type guard, which checks if the type implements index signature. How would one do that?

In other words, how to implement the body of this function:

function hasIndexSignature(o: complexunioninterface | { [index: string]: string }): o is { [index: string]: string } { return /* Help? */; }

Considering many types are objects, is the correct implementation this:

function hasIndexSignature(o: complexunioninterface | { [index: string]: string }): o is { [index: string]: string } { return typeof o === "object"; }

One way would be to implement a type guard for complexunioninterface and just negate that, but I'm interested if implementing the type guard for the index signature would make any sense and if it is possible.

最满意答案

我很感兴趣,如果为索引签名实现类型保护是有意义的,如果可能的话。

自定义类型防护是针对编译器无法推断出有关对象的高级知识的情况而设计的

所以真的,由你来决定测试的数量是多少就足够了。 我会说你想implement a type guard for complexunioninterface and just negate that,

I'm interested if implementing the type guard for the index signature would make any sense and if it is possible.

A custom type guard is designed for the case when a compiler cannot infer advanced knowledge you have about the objects.

So really, its up to you to decided how much of a test is sufficient. I would say go with your idea of implement a type guard for complexunioninterface and just negate that,

更多推荐

本文发布于:2023-08-06 09:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448335.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:索引   类型   如何在   check   runtime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!