问题描述
我想从传统的 JS 转向 TypeScript,因为我喜欢类似 C# 的语法.我的问题是我不知道如何在 TypeScript 中声明静态类.
I wanted to move to TypeScript from traditional JS because I like the C#-like syntax.My problem is that I can't find out how to declare static classes in TypeScript.
在 C# 中,我经常使用静态类来组织变量和方法,将它们放在一个命名类中,而不需要实例化一个对象.在 vanilla JS 中,我曾经用一个简单的 JS 对象来做到这一点:
In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object.In vanilla JS, I used to do this with a simple JS object:
var myStaticClass = {
property: 10,
method: function(){}
}
在 TypeScript 中,我宁愿采用 C-sharpy 方法,但似乎 TS 中不存在静态类.这个问题的合适解决方案是什么?
In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don't exist in TS. What is the appropriate solution for this problem ?
推荐答案
TypeScript 不是 C#,因此您不必期望 TypeScript 中的 C# 概念一定相同.问题是你为什么需要静态类?
TypeScript is not C#, so you shouldn't expect the same concepts of C# in TypeScript necessarily. The question is why do you want static classes?
在 C# 中,静态类只是一个不能被子类化并且必须只包含静态方法的类.C# 不允许在类之外定义函数.然而,在 TypeScript 中这是可能的.
In C# a static class is simply a class that cannot be subclassed and must contain only static methods. C# does not allow one to define functions outside of classes. In TypeScript this is possible, however.
如果您正在寻找一种将函数/方法放在命名空间(即非全局)中的方法,您可以考虑使用 TypeScript 的模块,例如
If you're looking for a way to put your functions/methods in a namespace (i.e. not global), you could consider using TypeScript's modules, e.g.
module M {
var s = "hello";
export function f() {
return s;
}
}
这样你就可以在外部访问 M.f() 而不是 s,并且你不能扩展模块.
So that you can access M.f() externally, but not s, and you cannot extend the module.
请参阅 TypeScript 规范 了解更多详情.
See the TypeScript specification for more details.
这篇关于TypeScript 静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!