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

查看:392
本文介绍了使用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);

如果在typescript playground中输入此代码,最后一行将标记为错误,名称A在当前范围中不存在。但这不是真的,该名称确实存在于当前范围内。我甚至可以改变变量声明为 var a:A = {member:foobar}; 没有来自编辑的投诉。浏览网页并找到其他问题后,我改变了接口的类,但我不能使用对象字面量创建实例。

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?

脚本操作的自动完成功能揭示了typescript甚至提供了一个方法 implements 。如何使用它?

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

推荐答案

没有办法运行时检查一个接口。

There is no way to runtime check an interface.

此外,根据有关论坛的讨论,我认为这很可能不会成为未来的功能Codeplex 。在讨论中有一些技术可能为你工作,虽然,它们主要是使用一些约定,使类型检查可能通过添加一个 __ implements 属性给你的所有对象。虽然是不一样的。

Additionally, I don't think it is likely that this will become a feature in the future according to the discussion on Codeplex. There are some techniques in that discussion that may work for you though, which are mostly about using some conventions to make something like type checking possible by adding an __implements property to all of your objects. It isn't really the same though.

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

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