typescript interface
interface Task{
name: String; //property
run(arg: any):void; //method
}
class MyTask implements Task{
name: String;
constructor(name: String) {
this.name = name;
}
run(arg: any): void {
console.log(`running: ${this.name}, arg: ${arg}`);
}
}
let myTask: Task = new MyTask('someTask');
myTask.run("test");
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
//difference b/w type and interface
/////////////////////// types reference another types
type FormElement = React.FormEvent<HTMLFormElement>;
// How to use?
const handleSubmit = (e: FormElement): void => { ... }
/////////////////////// interface create new types and
/////////////////////// also we can extend other interfaces
interface MyTodo {
text: string;
complete: boolean;
}
interface MyTodo2 extends MyTodo {
// also have all values from MyTodo
tags: string[]
}
// How to use?
const [todos, setTodos] = useState<MyTodo[]>([]);