Mohsen
Mohsen

Reputation: 1422

java code to typescript in nodejs conversion

I want to convert this java classes to nodejs but have problem with concept of understanding the generics.
I will be appreciated to describe the part generics and help me to convert to nodejs typescript

EditorState class:

import java.util.ArrayList;
import java.util.List;

public class EditorState{
private final String content;

public EditorState(String content){
    this.content = content;
}
public String getContent(){
    return content;
}
}

History class:

  public class History {

  private List<EditorState> states = new ArrayList<>();
  
  public void push(EditorState state){
     state.add(state);
  }  
  }

Upvotes: 0

Views: 1549

Answers (1)

Ethan Snow
Ethan Snow

Reputation: 455

Generics typings are not native to javascript, and at Runtime are completely ignored. In TypeScript They are a great way of identifying something about an object during development. A generic you probably already know For instance is Array<string>, or string[], which is an array of Strings. Your java code translated in typescript with Generics Could look like the following:

public class History<T> {
    private states:T[] = new Array// Array of T 
    public push(state:T):void {
        this.states.push(state) // assuming code you gave was a typo
    }
}
public class EditorState {
    private content:string
    constructor(content:string) {
        this.content = content
    }
    public getContent():string {
        return this.content
    }
}

//Usage

let hist:History<EditorState> = new History
let state = new EditorState("Something")
hist.push(state) //this is OK, as T is EditorState, and state is an Instance of EditorState
hist.push("Hello World") //This will raise an Error, as String is not of type EditorState

Here T is used as a generic type variable, which we define as EditorState when we create hist

Note that Generic Typing are ONLY in development, and are removed from the code that executes at runtime, but during development, will Enforce the typings. As such trying to history.push a String value will error on compilation

For more info on Generics there is some good documentation available: https://www.typescriptlang.org/docs/handbook/2/generics.html

Upvotes: 1

Related Questions