// Array, onde ja sei qual os tipos e qual o tamanho do Arraylet title: [number, string];title = [1, 'foo']; // corretotitle = [1, 'foo', true]; // errado
function logDetails(uid: number, item: string) { console.log(`A product with ${uid} has a title as ${item}.`);}logDetails(123, "sapato"); // Certo!logDetails("123", "sapato"); // Errado!// Corrigindofunction logDetails(uid: number | string, item: string) {...}logDetails("123", "sapato"); // Agora está correto
Mas o Type Aliasses é muito mais poderoso que isso...
// Type Aliastype Uid = number | string;// Varios funções, onde os parâmetros são do tipo Uid, que eu criei!function logDetails(uid: Uid, item: string){...}function logInfo(uid: Uid, user_name: string){...}
Outro exemplo:
type Platform = 'Windows' | 'Linux' | 'MacOS';function renderPlatform(platform: Platform) { return platform;}renderPlatform('ios'); // Retorna erro!renderPlatform('Windows'); // Retorna Windows
type AccountInfo = { id: number; name: string; email?: string; // O "?" significa que esse atributo é opcional (string | undefined)}const account: AccountInfo = { id: 123, name: "Junior" email: "junior@email.com"}type CharInfo = { nickname: string; level: number;}type PlayerInfo = AccountInfo & CharInfo; // Junta os dois tipos (Intersection)// Não é necessário passar na mesma ordem!const player: PlayerInfo = { id: 123, name: "Junior" email: "junior@email.com", nickname: "junior996"; level: 10;}
Semelhante ao private, porém, permite ser acessada dentro das subclasses também, já o private não, apenas dentro da própria classe.
class CharAccount extends UserAccount { private nickname: string; // nickname só pode ser acessado dentro dessa classe! readonly level: number; // readonly permite apenas ler, não editar a propriedade! constructor(name: string, age: number, nickname: string, level: number) { super(name, age) { this.nickname = nickname; this.level = level; } }}const newUser = new UserAccount("Marcos", 32, "marcos123", 82);newUser.nickname; // Error!newUser.level; // Funciona!newUser.level = 99 // Error! Só pode ser lida, não alterada
class UserAccount { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } logDetails(): void { console.log(`The player ${this.name} is ${this.age} years old`); } get getName() { console.log('---GET---'); return this.name; } set setName(name: string) { this.name = name; }}const user = new UserAccount('Junior', 23); // Cria uma instância de UserAccountuser.getName; // Acessa o getName, como se fosse uma propriedadeuser.setName = 'Jorge';
Um conjunto de dados para descrever a estrutura de um objeto. Exclusivamente para objetos.
interface Game { title: string; description: string; genre: string; platform: string[]; getSimilars: (title: string) => void; // Assinatura dos métodos}const theLastOfUs: Game = { title: 'The Last of Us', description: 'The best game in the world', genre: 'Action', platform: ['PS3', 'PS4'], getSimilars: (title: string) => { console.log(`Similar games to ${title}: Metro, Uncharted`); }};theLastOfUs.title; // "The Last of Us"
Os modifiers funcionam para as interfaces (public, private, readonly, protected)
Semelhante as classes, as interfaces também podem estender de outras interfaces.
interface Game { title: string; description: string; genre: string; platform: string[]; getSimilars: (title: string) => void;}const theLastOfUs: Game = { title: "The Last of Us", description: "The best game in the world", genre: "Action", platform: ["PS3", "PS4"], getSimilars: (title: string) => { console.log(`Similar games to ${title}: Metro, Uncharted`); }}interface DLC extends Game { originalGame: Game; // Objeto com todos as propriedades da interface Game newContent: string[];}const leftBehind: DLC = { title: "The Last of Us - Left Behind", description: "You play as Ellie", genre: "Action", platform: ["PS3", "PS4"], originalGame: theLastOfUs, // Objeto inteiro, declarado acima! newContent: ["3 hours story", "new caracters"] getSimilars: (title: string) => { console.log(`Similar games to ${title}: Metro, Uncharted`); }}
Nesse post, vimos um resumo de algumas funcionalidades do TypeScript. Nos próximos posts, iremos aprender mais afundo cada uma delas, além de outras funcionalidades.
Grande abraço e até a próxima!