[typescript] Types

Suyeon·2020년 11월 10일
0

Typescript

목록 보기
1/12
post-thumbnail

Why typescript?

  • Add types
  • Non javascript features (interface, generic)
  • Next-gen javascript features (like babel)
  • Rich configuration options
  • Less bugs

Types

  • boolean
  • number
  • string
  • array
  • object
  • tuple: An array with a fixed number of elements whose types are known, but need not be the same.
  • enum: Names to sets of numeric values.
  • unknown: Values may come from dynamic content or API.
  • any: Values from code that has been written without TypeScript or a 3rd party library.
  • void: The absence of having any type at all as the return type of functions that do not return a value. (console.log)
  • Null and Undefined
  • never: The type of values that never occur like returning an error.
//// boolean
let isDone: boolean = false; 

//// number
let num: number = 6; 

//// string
let color: string = "blue"; // (1)
let sentence: string = `Hello, my name is ${fullName}.` // (2)

//// array 
let list: number[] = [1, 2, 3]; // (1)
let list: Array<number> = [1, 2, 3]; // (2) generic array type

//// object
function create(o: object | null): void;
create({ prop: 0 });
create(null);

//// tuple
let x: [string, number];
x = ["hello", 10];
x.push('something'); // "push" is an exception. It is working.

//// enum
// First letter is uppercase(convention).
// Default value is "0".
enum Color {
  Red = 1,
  Green,
  Blue,
}
  
let c: Color = Color.Green;
  
//// unknown (better than any)
let userInput: unknown;
let userName: string;
  
userInput = 5;
userInput = 'Suyeon'
if(typeof userInput === 'string') {
	userName = userInput;
}
  
//// any
// Avoid using any if you can.
function getValue(key: string): any;
// OK, return value of 'getValue' is not checked
const str: string = getValue("myString");
  
//// void
function warnUser(): void { // (1) return nothing
  console.log("This is my warning message"); 
}

let unusable: void = undefined; // (2) return null or undefint 
unusable = null;

//// null and undefined
let u: undefined = undefined;
let n: null = null;

//// never
function error(message: string): never {
  throw new Error(message);
}

enum

  • Set of variables for abstraction
  • Readability
  • String / number
  • Key-value pair (reverse mapping)
profile
Hello World.

0개의 댓글