TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
npm install --save-dev @types/node
npm install --save-dev @types/jquery
npm install --save-dev @types/react
// Boolean
let isDone: boolean;
// Número
let decimal: number;
// String
let color: string;
// Array
let list: number[] = [1, 2, 3];
// Tuple
let x: [string, number] = ["hello", 10];
// Null e Undefined
let myUndefined: undefined;
let myNull: null;
// Multiplas opções
let stringOrNull: string | null = null;
// Qualquer coisa
let notSure: any = 4;
let meuArray: any[] = [1, "texto", false];
// Enums
enum Color {Red, Green, Blue}
let myColor: Color = Color.Green;
// Sem valor
function exibirMensagem(): void {
alert("Apenas uma mensagem");
}
// Classes
class MeuObjeto {}
let meuObj: MeuObjeto = new MeuObjeto
// Não vale a pena:
const meuTexto = "meu longo texto";
let validForm = false;
// Pode valer a pena:
let semValorInicial: number;
let multitipo: boolean | string = false;
no-inferrable-types
function printName(namedObj: { name: string }) {
console.log(namedObj.name);
}
let myObj = {size: 10, name: "Size 10 Object"};
printName(myObj);
interface NamedValue {
name: string;
}
function printName(namedObj: NamedValue) {
console.log(namedObj.name);
}
let myObj = {size: 10, name: "Size 10 Object"};
printName(myObj);
interface MinhaInterface {
user?: string; // opicional
readonly endereco: string; // apenas leitura
[index: number]: string; // definindo indices de acesso
}
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
class UserService {
getAllUsers() {
return fetch('/users');
}
}
interface User {
id: number;
name: string;
age?: number;
}
class UserService {
getUsers(): Promise<User> {
return fetch('/user');
}
}
function identity(arg: number): number {
return arg;
}
function identity(arg: any): any {
return arg;
}
function identity<T>(arg: T): T {
return arg;
}