type and interface typescript
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");
// for starters:
// interfaces and types are very similar, they just differ in syntax
// interface
interface Car {
name: string;
brand: string;
price: number;
}
// type
type Car = {
name: string;
brand: string;
price: number;
}
// interface
interface Car extends Vehicle {
name: string;
brand: string;
price: number;
}
// type
type Car = Vehicle & {
name: string;
brand: string;
price: number;
}
//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[]>([]);