Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Created July 25, 2019 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaoyunyang/c4e52b41da9135cc35b565d44ea59c1b to your computer and use it in GitHub Desktop.
Save xiaoyunyang/c4e52b41da9135cc35b565d44ea59c1b to your computer and use it in GitHub Desktop.
TypeScript vs JavaScript example

The example is taken from TypeScript's quick start tutorial

In JavaScript

const greeter = (person) => "hello "+person;
greeter([1,2,3]) // "hello 1,2,3"

In TypeScript

const greeter = (person) => "hello "+person; // error: Parameter 'person' implicitly has an 'any' type.

TSError: ⨯ Unable to compile TypeScript: index.ts:1:18 - error TS7006: Parameter 'person' implicitly has an 'any' type.

Unable to compile - TypeScript provides static typing.

const greeter = (person: string) => "hello " + person;
greeter([1,2,3]) // X3 error: Type 'number' is not assignable to type 'string'

The error is printed out three times because there are three numbers in the array.

const greeter = (person: string) => "hello " + person;
greeter([1,2,3]) // error: Type 'number' is not assignable to type 'string'
const greeter = (person: string) => "hello " + person;
greeter(["1","2","3"]) // error: Argument of type 'string[]' is not assignable to parameter of type 'string'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment