[英]Which will be better declaration go to with TypeScript?
This is a simple question, but during my migration to TypeScript, I'm seeing that in many cases my code could take these two directions... which one could be a better direction to go with: class.ts
or interface.ts
? 这是一个简单的问题,但是在我迁移到TypeScript的过程中,我发现在许多情况下,我的代码可以遵循这两个方向...哪个方向更好: class.ts
或interface.ts
?
class.ts 类
export class ActionSet {
constructor(private name: string) {}
get ACTION(): string {
return this.name;
}
get PENDING(): string {
return `${this.name}_PENDING`;
}
get FULFILLED(): string {
return `${this.name}_FULFILLED`;
}
get REJECTED(): string {
return `${this.name}_REJECTED`;
}
}
export function createActionSet(name: string): ActionSet {
return new ActionSet(name);
}
interface.ts 接口
export interface IActionSet {
ACTION: string;
PENDING: string;
FULFILLED: string;
REJECTED: string;
}
export function createActionSet(name: string): IActionSet {
return {
ACTION: name,
PENDING: `${name}_PENDING`,
FULFILLED: `${name}_FULFILLED`,
REJECTED: `${name}_REJECTED`
};
}
A more visual way: 更直观的方式:
Due to ActionSet
is not being used in many places, will it be worth to create a class for it? 由于ActionSet
不在许多地方使用,是否值得为其创建一个类? or is this implementation an overkill? 还是这种实施方式过于矫kill过正?
The two solutions are fine. 两种解决方案都很好。 There is no bad choice here. 这里没有不好的选择。 So, it is not a real answer but a comment, here. 因此,这里不是真正的答案,而是评论。
class
为什么喜欢class
instanceof
; 在运行时,您可以使用instanceof
; interface
) and the implementation (the factory); 您不必分别编写合同( interface
)和实现(工厂); interface
为什么偏爱interface
Object.keys
, Object.assign
etc., on the objects; 在运行时,可以在对象上使用Object.keys
, Object.assign
等。 A small tip: do not use a prefix I
for interfaces. 一个小技巧:不要在接口中使用前缀I
Otherwise, which prefix will you use for a type like: 否则,将为以下类型使用哪个前缀:
type WhichPrefixForThatType = MyInterface | boolean;
TypeScript is JavaScript with types. TypeScript是具有类型的JavaScript。 It is not an independent language. 它不是独立的语言。 So, to evaluate what are good practices in TypeScript, remember to look at the equivalent JavaScript code. 因此,要评估TypeScript的良好做法,请记住查看等效的JavaScript代码。
You can compare the version with a class: 您可以将版本与类进行比较:
export class ActionSet {
constructor(name) {
this.name = name;
}
get ACTION() {
return this.name;
}
get PENDING() {
return `${this.name}_PENDING`;
}
get FULFILLED() {
return `${this.name}_FULFILLED`;
}
get REJECTED() {
return `${this.name}_REJECTED`;
}
}
export function createActionSet(name) {
return new ActionSet(name);
}
The version with an interface: 具有接口的版本:
export function createActionSet(name) {
return Object.freeze({
ACTION: name,
PENDING: `${name}_PENDING`,
FULFILLED: `${name}_FULFILLED`,
REJECTED: `${name}_REJECTED`
});
}
In your example, the second one seems to be simpler to write and to read. 在您的示例中,第二个似乎更易于编写和阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.