Typescript with React - TwoGears/hakomo-guides GitHub Wiki

What is Typescript?

TypeScript was created by Microsoft and was released in 2012 after two years of development. Typescript is a language built on javascript. It adds static type definitions and can find and check errors before runtime.

How it works?

JavaScript is dynamically typed. Therefore, programs written in JavaScript do not know the data type of a variable until that variable is assigned a value at runtime. The variable can be reassigned or coerced into a value of a different type with no issues or warning. This can result in bugs that are often overlooked, especially in large applications. TypeScript, on the other hand, uses static typing. Variables can be given a type when they are declared. TypeScript will check types at compile time, and throw an error if the variable is ever given a value of a different type. However, the error does not prevent the code from executing. The code will still be compiled into plain JavaScript and run normally. In this way, TypeScript is kind of like a “spellcheck” for your code. It will let you know when something looks off, but it won’t change how your code runs.

Why to use it?

  • TypeScript compiles into JavaScript code and you can choose which version of JavaScript you would like to target (including ES3, ES5 and ES6). This means that TypeScript is not only a superset of the current version of JavaScript (ES5), but also a superset of the upcoming version of JavaScript (ES6).
  • Produce code that is easier to understand and refactor
  • You might get type-checking errors, but that won't stop you from running the resulting JavaScript. clean and better code easy to refactor

How to use it with React projects?

  • npx create-react-app my-app --template typescript - for react js project
  • npx react-native init MyApp --template react-native-template-typescript - for react-native project
  • only in dev environment

Types

  • primitives: string, number, boolean function greet(personName: string) { console.log(Hello ${personName}); }
  • array type Person: { name: string; gender: string; age?: number; } const people: Person[] number[], string[], persons[], etc.
  • object - Object types can also specify that some or all of their properties are optional. To do this, add a ? after the property name const person: { name: string; gender: string; age?: number; } = { name: “Mihaela”, gender: “female”, age: 30 }
  • any - any can be used whenever you don’t want a particular value to cause type checking errors. Avoid this, because any isn’t type-checked.
  • tuples - fixed-length array: [number, string, string]
  • functions - TypeScript allows to specify the types of both the input and output values of functions. function greet(name: string) { console.log(name); } function getFavoriteNumber(): number { return 26; }
  • unions id: number | string
  • type alias - extract types type Person = { name: string; age: number; }; function person(person: Person) { console.log(person.name); }
  • interfaces - they are almost like type alias but with some differences: Interfaces are basically a way to describe data shapes, for example, an object. Type is a definition of a type of data, for example, a union, primitive, intersection, tuple, or any other type. One thing that’s possible to do with interfaces but are not with types is declaration merging. Declaration merging happens when the TypeScript compiler merges two or more interfaces that share the same name into only one declaration. Declaration merging does not work with types. If we try to create two types with the same names, but with different properties, TypeScript would still throw us an error. Interfaces work better with objects and method objects, and types are better to work with functions, complex types, etc. https://blog.logrocket.com/types-vs-interfaces-in-typescript/ interface Song { artistName: string; };

interface Song { songName: string; };

type Song { songName: string;

} type Artist { artistName: string;

} const

const song: Song = { artistName: "Freddie", songName: "The Chain" };

  • literals - exact value type Easing = "ease-in" | "ease-out" | "ease-in-out"; class UIElement { animate(dx: number, dy: number, easing: Easing) { }
  • enums - An enum is a group of named constant values, can be numbers or strings, or both (Heterogeneous). By default, TypeScript enums are number-based. https://blog.logrocket.com/writing-readable-code-with-typescript-enums-a84864f340e9/ enum Weekend { Friday: “Friday”, (0) Saturday, (1) Sunday (2) } if (value === Weekend.Friday || value === Weekend.Sunday){ console.log('You choose a weekend'); console.log(value); }

Files in typescript

TypeScript has two main kinds of files:

  • .D.TS - Declaration files are files that describe the shape of an existing JavaScript codebase to TypeScript. They contain only type information. These files don't produce .js outputs; they are only used for typechecking.
  • .TS - .ts files are implementation files that contain types and executable code. These are the files that produce .js outputs, and are where you'd normally write your code.
  • .TSX - jsx with typescript

Disadvantages

  • One more JavaScript to learn - It would be relatively easy for JS developers to learn TS. However, despite this similarity, they still need to invest time and effort in learning types and some TS-specific constructs. So, if your company plans to move to TypeScript and have JS devs with no previous experience with TS, they won’t hit 100% productivity immediately.
  • More code to write - This has the potential of slowing down the development process.

Best practices

  • any - don’t use any as a type unless you are in the process of migrating a JavaScript project to TypeScript.
  • configuration - tsconfig.json, ESLint, Prettier, VS Code extensions and settings.
  • no explicit type declarations for variable or parameters with literal values - instead of const foo: number = 10, write const foo = 10 no empty interface declarations - interface Foo { name: string}