




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
livro programação typescript, estrutura da linguagem, compiladores, javascript
Tipologia: Manuais, Projetos, Pesquisas
Oferta por tempo limitado
Compartilhado em 22/10/2019
1 documento
1 / 381
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Em oferta
Introduction Getting Started Why TypeScript JavaScript Equality References Null vs. Undefined this Closure Number Truthy Future JavaScript Now Classes Classes Emit Arrow Functions Rest Parameters let const Destructuring Spread Operator for...of Iterators Template Strings Promise Generators Async Await Project Compilation Context tsconfig.json Which Files?
React Non React JSX Options noImplicitAny strictNullChecks Errors in TypeScript Interpreting Errors Common Errors NPM Testing Jest Cypress Tools Prettier Husky ESLint Changelog TIPs String Based Enums Nominal Typing Stateful Functions Currying Type Instantiation Lazy Object Literal Initialization Classes are Useful Avoid Export Default Limit Property Setters outFile caution JQuery tips static constructors singleton pattern Function parameters
Build Toggles Barrel Create Arrays Typesafe Event Emitter StyleGuide TypeScript Compiler Internals Program AST TIP: Visit Children TIP: SyntaxKind enum Trivia Scanner Parser Parser Functions Binder Binder Functions Binder Declarations Binder Container Binder SymbolTable Binder Error Reporting Checker Checker Diagnostics Checker Error Reporting Emitter Emitter Functions Emitter SourceMaps Contributing
of great value link Thanks, this is a great book link Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link This is sweet! So many #typescript goodies! link
If you are here to read the book online get started.
Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.
Filipino Italian Chinese Russian Portuguese Japanese Spanish Korean
You can also download one of the following:
EPUB for iPad, iPhone, Mac PDF for Windows and others MOBI for Kindle
All the amazing contributors
Introduction
Share URL: http://basarat.gitbooks.io/typescript/
Introduction
additional setup (e.g. npm modules), we will link you to the code sample before presenting the code. e.g. this/will/be/the/link/to/the/code.ts // This will be the code under discussion
With a dev setup out of the way let's jump into TypeScript syntax.
Getting Started
There are two main goals of TypeScript:
Provide an optional type system for JavaScript. Provide planned features from future JavaScript editions to current JavaScript engines
The desire for these goals is motivated below.
You might be wondering " Why add types to JavaScript? "
Types have proven ability to enhance code quality and understandability. Large teams (Google, Microsoft, Facebook) have continually arrived at this conclusion. Specifically:
Types increase your agility when doing refactoring. It's better for the compiler to catch errors than to have things fail at runtime. Types are one of the best forms of documentation you can have. The function signature is a theorem and the function body is the proof.
However, types have a way of being unnecessarily ceremonious. TypeScript is very particular about keeping the barrier to entry as low as possible. Here's how:
TypeScript provides compile time type safety for your JavaScript code. This is no surprise given its name. The great thing is that the types are completely optional. Your JavaScript code .js file can be renamed to a .ts file and TypeScript will still give you back valid .js equivalent to the original JavaScript file. TypeScript is intentionally and strictly a superset of JavaScript with optional Type checking.
TypeScript will try to infer as much of the type information as it can in order to give you type safety with minimal cost of productivity during code development. For example, in the following example TypeScript will know that foo is of type number below and will give an error on the second line as shown:
Why TypeScript
minimum cognitive overload, types are structural. This means that duck typing is a first class language construct. Consider the following example. The function iTakePoint2D will accept anything that contains all the things ( x and y ) it expects:
interface Point2D { x: number; y: number; } interface Point3D { x: number; y: number; z: number; } var point2D: Point2D = { x: 0, y: 10 } var point3D: Point3D = { x: 0, y: 10, z: 20 } function iTakePoint2D(point: Point2D) { /* do something */ } iTakePoint2D(point2D); // exact match okay iTakePoint2D(point3D); // extra information okay iTakePoint2D({ x: 0 }); // Error: missing information y
To make it easy for you to migrate your JavaScript code to TypeScript, even if there are compilation errors, by default TypeScript will emit valid JavaScript the best that it can. e.g.
var foo = 123; foo = '456'; // Error: cannot assign a string to a number
will emit the following js:
var foo = 123; foo = '456';
So you can incrementally upgrade your JavaScript code to TypeScript. This is very different from how many other language compilers work and yet another reason to move to TypeScript.
A major design goal of TypeScript was to make it possible for you to safely and easily use existing JavaScript libraries in TypeScript. TypeScript does this by means of declaration. TypeScript provides you with a sliding scale of how much or how little effort you want to put
Why TypeScript
in your declarations, the more effort you put the more type safety + code intelligence you get. Note that definitions for most of the popular JavaScript libraries have already been written for you by the DefinitelyTyped community so for most purposes either:
As a quick example of how you would author your own declaration file, consider a trivial example of jquery. By default (as is to be expected of good JS code) TypeScript expects you to declare (i.e. use var somewhere) before you use a variable
$('.awesome').show(); // Error: cannot find name $
As a quick fix you can tell TypeScript that there is indeed something called $ :
declare var $: any; $('.awesome').show(); // Okay!
If you want you can build on this basic definition and provide more information to help protect you from errors:
declare var $: { (selector:string): any; }; $('.awesome').show(); // Okay! $(123).show(); // Error: selector needs to be a string
We will discuss the details of creating TypeScript definitions for existing JavaScript in detail later once you know more about TypeScript (e.g. stuff like interface and the any ).
TypeScript provides a number of features that are planned in ES6 for current JavaScript engines (that only support ES5 etc). The TypeScript team is actively adding these features and this list is only going to get bigger over time and we will cover this in its own section. But just as a specimen here is an example of a class:
Why TypeScript
There were (and will continue to be) a lot of competitors in Some syntax to JavaScript compilers. TypeScript is different from them in that Your JavaScript is TypeScript. Here's a diagram:
However, it does mean that you need to learn JavaScript (the good news is you only need to learn JavaScript ). TypeScript is just standardizing all the ways you provide good documentation on JavaScript.
Just giving you a new syntax doesn't help catch bugs - but might help you write cleaner / less bugs (e.g. CoffeeScript). Creating a new language abstracts you too far from your runtimes and communities - but might help on-board you easier if its an already familiar flavour (e.g. Dart - closer for
JavaScript
Java / C# devs).
TypeScript is just JavaScript with docs.
JSNext is open to interpretation - not everything proposed for the next version of JS actually makes it to browsers. TypeScript only adds support for proposals once they reach stage 3.
TypeScript will try to protect you from portions of JavaScript that never worked (so you don't need to remember this stuff):
[] + []; // JavaScript will give you "" (which makes little sense), TypeScript will er ror // // other things that are nonsensical in JavaScript // - don't give a runtime error (making debugging hard) // - but TypeScript will give a compile time error (making debugging unnecessary) // {} + []; // JS : 0, TS Error [] + {}; // JS : "[object Object]", TS Error {} + {}; // JS : NaN or [object Object][object Object] depending upon browser, TS Error "hello" - 1; // JS : NaN, TS Error function add(a,b) { return a + b; // JS : undefined, TS Error 'unreachable code detected' }
Essentially TypeScript is linting JavaScript. Just doing a better job at it than other linters that don't have type information.
That said TypeScript is very pragmatic about the fact that you do write JavaScript so there are some things about JavaScript that you still need to know in order to not be caught off- guard. Let's discuss them next.
Note: TypeScript is a superset of JavaScript. Just with documentation that can actually be used by compilers / IDEs ;)
JavaScript
One thing to be careful about in JavaScript is the difference between == and ===. As JavaScript tries to be resilient against programming errors == tries to do type coercion between two variables e.g. converts a string to a number so that you can compare with a number as shown below:
console.log(5 == "5"); // true , TS Error console.log(5 === "5"); // false , TS Error
However, the choices JavaScript makes are not always ideal. For example, in the below example the first statement is false because "" and "0" are both strings and are clearly not equal. However, in the second case both 0 and the empty string ( "" ) are falsy (i.e. behave like false ) and are therefore equal with respect to ==. Both statements are false when you use ===.
console.log("" == "0"); // false console.log(0 == ""); // true console.log("" === "0"); // false console.log(0 === ""); // false
Note that string == number and string === number are both compile time errors in TypeScript, so you don't normally need to worry about this.
Similar to == vs. === , there is != vs. !==
So ProTip: Always use === and !== except for null checks, which we cover later.
If you want to compare two objects for structural equality == / === are not sufficient. e.g.
console.log({a:123} == {a:123}); // False console.log({a:123} === {a:123}); // False
To do such checks use the deep-equal npm package e.g.
Equality
import * as deepEqual from "deep-equal"; console.log(deepEqual({a:123},{a:123})); // True
However, quite commonly you don't need deep checks and all you really need is to check by some id e.g.
type IdDisplay = { id: string, display: string } const list: IdDisplay[] = [ { id: 'foo', display: 'Foo Select' }, { id: 'bar', display: 'Bar Select' }, ] const fooIndex = list.map(i => i.id).indexOf('foo'); console.log(fooIndex); // 0
Equality