使用 Typescript 检查接口类型 [英] Interface type check with Typescript

查看:32
本文介绍了使用 Typescript 检查接口类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题直接类似于使用 TypeScript 进行类类型检查

我需要在运行时找出 any 类型的变量是否实现了接口.这是我的代码:

I need to find out at runtime if a variable of type any implements an interface. Here's my code:

interface A{
    member:string;
}

var a:any={member:"foobar"};

if(a instanceof A) alert(a.member);

如果在打字稿操场中输入此代码,最后一行将被标记为错误,名称 A 在当前范围内不存在".但事实并非如此,该名称确实存在于当前作用域中.我什至可以将变量声明更改为 var a:A={member:"foobar"}; 而不会有编辑器的抱怨.在浏览网页并在 SO 上找到另一个问题后,我将接口更改为类,但随后我无法使用对象文字来创建实例.

If you enter this code in the typescript playground, the last line will be marked as an error, "The name A does not exist in the current scope". But that isn't true, the name does exist in the current scope. I can even change the variable declaration to var a:A={member:"foobar"}; without complaints from the editor. After browsing the web and finding the other question on SO I changed the interface to a class but then I can't use object literals to create instances.

我想知道类型 A 怎么会像这样消失,但查看生成的 javascript 可以解释问题:

I wondered how the type A could vanish like that but a look at the generated javascript explains the problem:

var a = {
    member: "foobar"
};
if(a instanceof A) {
    alert(a.member);
}

没有将 A 表示为接口,因此无法进行运行时类型检查.

There is no representation of A as an interface, therefore no runtime type checks are possible.

我知道 javascript 作为一种动态语言没有接口的概念.有没有办法对接口进行类型检查?

I understand that javascript as a dynamic language has no concept of interfaces. Is there any way to type check for interfaces?

打字稿游乐场的自动完成显示打字稿甚至提供了一种方法implements.我该如何使用它?

The typescript playground's autocompletion reveals that typescript even offers a method implements. How can I use it ?

推荐答案

你可以在没有 instanceof 关键字的情况下实现你想要的,因为你现在可以编写自定义类型保护:

You can achieve what you want without the instanceof keyword as you can write custom type guards now:

interface A{
    member:string;
}

function instanceOfA(object: any): object is A {
    return 'member' in object;
}

var a:any={member:"foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}

成员众多

如果你需要检查很多成员来确定一个对象是否与你的类型匹配,你可以改为添加一个鉴别器.以下是最基本的示例,需要您管理自己的鉴别器……您需要更深入地了解这些模式,以确保避免重复鉴别器.

Lots of Members

If you need to check a lot of members to determine whether an object matches your type, you could instead add a discriminator. The below is the most basic example, and requires you to manage your own discriminators... you'd need to get deeper into the patterns to ensure you avoid duplicate discriminators.

interface A{
    discriminator: 'I-AM-A';
    member:string;
}

function instanceOfA(object: any): object is A {
    return object.discriminator === 'I-AM-A';
}

var a:any = {discriminator: 'I-AM-A', member:"foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}

这篇关于使用 Typescript 检查接口类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆