我不确定这是否有意义,因为许多类型都是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,
更多推荐
发布评论