TypeScript 变量名作为接口类型? [英] TypeScript variable name as interface type?

查看:25
本文介绍了TypeScript 变量名作为接口类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段难以理解的 TypeScript 代码.我是 TypeScript 的新手.

I have a piece of TypeScript code that I'm having trouble to understand. I am fairly new to TypeScript.

export const TerminalWidgetOptions = Symbol("TerminalWidgetOptions");
export interface TerminalWidgetOptions {
    endpoint: Endpoint.Options,
    id: string,
    caption: string,
    label: string
    destroyTermOnClose: boolean
}

谁能告诉我上面的代码到底发生了什么?我所理解的是创建了一个名为 TerminalWidgetOptions 的接口,它强制参数 endpointidcaptionlabeldestroyTermOnClose 在实现到一个类中时.我虽然不太明白上面的行.因此,显然创建了一个常量,只能设置一次,然后保持这种状态,对吗?但是这个常量怎么能和接口类型同名呢?Symbol("TerminalWidgetOptions"); 的赋值很明确.来自 Symbol 函数的内容被放入常量中.

Could someone tell me what exactly happens in the above code? What I do understand is that an interface of the name TerminalWidgetOptions is created and it forces the parameters endpoint, id, caption, label and destroyTermOnClose upon implementation into a class. I though don't quite understand the above line. So, apparently a constant is created, that can only be set once and then stays that way, right? But how can this constant have the same name as the interface type? The assignment of Symbol("TerminalWidgetOptions"); is clear. What comes from the Symbol function is put into the constant.

这或多或少正确吗?

推荐答案

在 TypeScript 中,您可以为变量/常量、接口甚至命名空间使用相同的名称.

In TypeScript you can have the same name for a variable/constant, an interface and even a namespace.

TypeScript 根据上下文理解您所指的内容.请记住,接口只是对编译器和程序员的类型提示,它们在代码编译时完全消失,因此生成的 JavaScript 代码中不会发生冲突.

TypeScript understands what you're referring to based on context. Remember that interfaces are just type hints to the compiler and the programmer, they disappear completely when the code is compiled, so there are no conflicts in the resulting JavaScript code.

当您使用 TerminalWidgetOptions 所指的内容不明确时,没有用例:

There is not a use case when what you're referring to with TerminalWidgetOptions is ambiguous:

class Klass implements TerminalWidgetOptions { // interface

someFunction(TerminalWidgetOptions); // constant

let t = TerminalWidgetOptions; // constant

事实上,当您定义一个类时,您正在做类似的事情.通过定义一个类,你既声明了一个类型又定义了一个值

In fact, when you define a class, you're doing something similar. By defining a class you are both declaring a type and defining a value

const d = Klass; // d now is like the constructor of Klass (a value, something that exists)
doSomething<Klass>(); // Here, Klass is a pure type (an abstraction)

区别?

  • 类型表示函数对象的形状".
  • 值是在程序中物理地"存在的东西(一个对象)

因此,接口只是一种类型.变量只是一个值.一个类既是一个类型(定义该类的实例的接口)又是一个值(是一个构造该类型实例的函数)

So, an interface is just a type. A variable is just a value. A class is both a type (defines the interface of instances of that class) and value (is a function that constructs instances of the type)

希望这能让你更清楚

这篇关于TypeScript 变量名作为接口类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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