Using TypeScript

General Principles

Types

Primitive Types

Collection Types

Object Types

interface Sportsball {
  HomeTeam: string,
  AwayTeam: string,
  HomeScore: number,
  AwayScore: number
}

You can also add readonly to a property to make it immutable. #immutability:

interface Sportsball {
  readonly HomeTeam: string,
  readonly AwayTeam: string,
  HomeScore: number,
  AwayScore: number
}

Enums

Unions

Unions are an alternative to Enums. Examples of unions:

type SportsType = 'Football' | 'Baseball' | 'Basketball' | 'Hockey'

Annotations

Type Assertions

Generics

interface GenericSportsBall<TeamType, ScoreType> {
  HomeTeam: TeamType,
  AwayTeam: AwayType,
  HomeScore: ScoreType,
  AwayScore: ScoreType
}
interface GenericSportsBall<TeamType extends String, ScoreType extends Number> {}
const mergeMaps = 
      (m1: Map<KeyType, ValType>,
      m2: Map<KeyType, ValType>
      ): Map<KeyType, ValType => ...

Utility Types

tsconfig.json

.d.ts files

TypeScript x React

type blogProps = { title: string, content?: string }
const BlogPost = ({title, content }: blogProps) => <div />
// or
const BlogPost = (props:blogProps) => <div />
// or
const BlogPost: FunctionComponent<BlogProps> = ({ title, content }) => <div/>

TypeScript x JSON

interface MyObj {
  myString: string;
  myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
{
"compilerOptions": {
  "resolveJsonModule": true,
  "esModuleInterop": true  

}