본문 바로가기

KnowledgeBase

Cheat - Typescript

변수선언 : Var (일반), Let (블럭범위), Const (상수선언)

var 일반적인 변수선언, let 선언된 블럭범위안에서만 사용가능, const 상수선언

자료형 : Var Type

//Number
let _num :number = 10.345;
_num.toFixed(2); // "10.35"
_num.valueOf(); // 10.345
_num.toString(); // "10.345"
_num.toPrecision(2); //"10"

//-------------------------------------------------------------------------------------

//String
let _str:string = "Typescript";
_str.charAt(1); // y
_str.split(""); //["T", "y", "p", "e", "s", "c", "r", "i", "p", "t"]
_str.indexOf("s"); //4 , gives -1 is the value does not exist in the string.
_str.replace("Type", "Coffee"); //"Coffeescript"
_str.trim(); //"Typescript"
_str.substr(4, _str.length); //"script"
_str.substring(4, 10); //"script"
_str.toUpperCase();//"TYPESCRIPT"
_str.toLowerCase();//"typescript"

//-------------------------------------------------------------------------------------

//Boolean
let bflag :boolean = 1;
let status :boolean = true;

//-------------------------------------------------------------------------------------

//Any
let a :any = 123
a = "hello world"; // changing type will not give any error.

//-------------------------------------------------------------------------------------

//Void
function testfunc():void{
 //code here
}

//-------------------------------------------------------------------------------------

//Enum
enum Directions {
North,
South,
East,
West
}

console.log(Directions.North); // output is  0
console.log(Directions["North"]); // output is 0
console.log(Directions[0]); //output is North

enum Directions {
North = 0,
South = 1, 
East =2,
West =3
}

enum Directions {
North = 5,
South, // will be 6
East, // 7
West // 8
}

enum Directions {
North = 5,
South = 4,
East = 6,
West = 8
}

enum Directions {
    North = "N",
    South = "S",
    East = "E",
    West = "W"
}

//-------------------------------------------------------------------------------------

//Array
let months: Array<string> = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; //array with all string values.

let years: Array<number> = [2015, 2016, 2017, 2018, 2019]; //array will all numbers

let month_year: Array<string | number> = ["Jan", 2015, "Feb", 2016]; //array with string and numbers mixed.

let alltypes: Array<any> = [true, false, "Harry", 2000, { "a": "50", "b": "20" }]; //array of all types boolean, string , number , object etc.

//Array - Length : 배열길이
let months: Array<string> = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; //array with all string values.

console.log(months.length);  // 12

//Array - Reverse : 역순정렬
let months: Array<string> = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; //array with all string values.

console.log(months.reverse());  //  ["Dec", "Nov", "Oct", "Sept", "Aug", "July", "June", "May", "April", "March", "Feb", "Jan"]

//Array - Sort : 순정렬
let months: Array<string> = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; //array with all string values.

console.log(months.sort()); // ["April", "Aug", "Dec", "Feb", "Jan", "July", "June", "March", "May", "Nov", "Oct", "Sept"]

//Array - Pop : LIFO
let months: Array<string> = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; //array with all string values.				

console.log(months.pop()); //Dec

//Array - Shift : FIFO
let months: Array<string> = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; //array with all string values.			

console.log(months.shift()); // Jan

//Array - Push : 맨뒤에 넣기
let years: Array<number> = [2015, 2016, 2017, 2018, 2019]; //array will all numbers			
console.log(years.push(2020)); 			
years.forEach(function(yrs, i) {			
  console.log(yrs); // 2015 , 2016,2017, 2018, 2019,2020				
});

//Array - Concat : 배열결합
let array1: Array<number> = [10, 20, 30]; 			
let array2: Array<number> = [100, 200, 300];			
console.log(array1.concat(array2)); //[10, 20, 30, 100, 200, 300]

연산자

= : 대입연산자,  == 느슨한 비교 ( 10 == "10" 은 같은거), === 빡쎈 비교 (10 === "10"은 다른거)

일반 반복

// For loop
var students = new Array("John", "Ann");
for (i=0; i<students.length; i++)
{
    console.log(students[i]);
}

// While
while(condition)
{ }

// Do While
do { } while(condition)

배열 반복:

// INDEX
let years: Array<number> = [ 2016, 2017, 2018, 2019]; //array will all numbers		
years[0]; // output will be 2016			
years[1]; // output will be 2017			
years[2]; // output will be 2018			
years[3]; // output will be 2019

// For
let years: Array<number> = [ 2016, 2017, 2018, 2019]; 
for (let i=0;i<=years.length; i++) {
     console.log(years[i]);
}
Output:
2016
2017
2018
2019

// For In
let years: Array<number> = [ 2016, 2017, 2018, 2019]; 
for (let i in years) {
     console.log(years[i])
}
Output:
2016
2017
2018
2019

// For Of
let years: Array<number> = [ 2016, 2017, 2018, 2019]; 
for (let  i of years) {
     console.log(i)
}
Output:
2016
2017
2018
2019

// ForEach
let years: Array<number> = [ 2016, 2017, 2018, 2019]; 
years.forEach(function(yrs, i) {
  console.log(yrs);
});
Output:
2016
2017
2018
2019

조건문

- if (condition) { } else { }
- if (condition1) { } else if(condition2) { } else { }

클래스 : Class

class nameofclass {
     //define your properties here

    constructor() {
     // initialize your properties here
    }
 
   //define methods for class
}


class Students {
    age : number;
    name : string;
    roll_no : number;
    
    constructor(age: number, name:string, roll_no: number) {
        this.age = age;
        this.name = name;
        this.roll_no = roll_no;
    }

    getRollNo(): number {
        return this.roll_no;
    }

    getName() : string {
        return this.name;
    }

    getAge() : number {
        return this.age;
    }
} 


let student_details = new Students(15, "Harry John", 33);
student_details.getAge(); // 15
student_details.getName(); // Harry John

상속 : Extends

class A {
     //define your properties here

    constructor() {
     // initialize your properties here
    }
 
   //define methods for class

}

class B extends A {
 //define your properties here

    constructor() {
     // initialize your properties here
    }
 
   //define methods for class

}

//---------------------------------------------------------------------

class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    getName(): string {
        return this.name;
    }

    getAge(): number {
        return this.age;
    }
}

class Student extends Person {
    tmarks: number;
    getMarks(): number {
        return this.tmarks;
    }

    setMarks(tmarks) {
        this.tmarks = tmarks;
    }
}

let _std1 = new Student('Sheena', 24);
_std1.getAge(); // output is 24
_std1.setMarks(500);
_std1.getMarks(); // output is 500

//---------------------------------------------------------------------

class Person {
    protected name: string;
    protected age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    private getName(): string {
        return this.name;
    }

    getDetails(): string {
        return "Name is "+ this.getName();
    }
}

class Student extends Person {
    tmarks: number;
    constructor(name: string, age: number, tmarks: number) {
        super(name, age);  
        this.tmarks = tmarks;    
    }
    getMarks(): number {
        return this.tmarks;
    }

    getFullName(): string {
        return this.name;
    }
    
    setMarks(tmarks) {
        this.tmarks = tmarks;
    }
}

let _std1 = new Student('Sheena', 24, 500);
_std1.getMarks(); // output is 500
_std1.getFullName(); // output is Sheena
_std1.getDetails(); // output is Name is Sheena

인터페이스 : Interface, Implements

클래스, 함수, 변수가 지켜야 하는 룰 선언

interface Dimension {
    width: string;
    height: string;
}

// 변수에서 Interface 구현
let _imagedim: Dimension = {
    width: "100px",
    height: "200px"
};

// 함수의 리턴타입으로 Interface 구현
function getDimension() : Dimension {
    let width = "300px";
    let height = "250px";
    return {
        width: width,
        height: height
    }
}

// 함수의 파라메터로 Interface 구현
function getDimension(dim: Dimension) : string {
    let finaldim  = dim.width +"-"+ dim.height;
    return finaldim;
}

getDimension({width:"300px", height:"250px"}); // will get "300px-250px" 

// Interface 구현 클래스
interface Dimension {
    width : string,
    height: string,
    getWidth(): string; 
}

class Shapes implements Dimension {
    width: string;
    height: string;
    constructor (width:string, height:string) {
        this.width = width;
        this.height = height;
    }
    getWidth() {
        return this.width;
    }
}

함수 : Function

// ? 는 옵셔널로 호출시 생략할 수 있음, 생략했는데 사용하면 "undefined"로 간주되어 사용됨
function getName(firstname: string, lastname?: string): string {
    return firstname + lastname;
}

let a = getName("John"); // will return Johnundefined.
let b = getName("John", "Harry"); // will return JohnHarry
let c = getName("John", "H", "Harry"); // error TS2554: Expected 1-2 arguments, but got 3.

// 파라메터에 default값 정의 가능
function getName(firstname: string, lastname = "Harry"): string {
    return firstname + lastname;
}

let a = getName("John"); // will return JohnHarry
let b = getName("John", "H"); // will return JohnH

// 가변인자 파라메터 정의 가능
function testFunc(a: string, ...arr: string[]) :string {
    return a + arr.join("");
}

let a = testFunc("Monday", "Tuesday", "Wednesday", "Thursday"); // will get output as MondayTuesdayWednesdayThursday

화살표 함수 : Arrow Function

일반 함수가 자신의 this 영역을 갖는 것과 다르게, 화살표 함수는 부모의 this영역을 공유한다.
이는, 콜백함수나, 이벤트 핸들러, 타이밍 함수내부를 간단한 문법으로 표현하기 용이하게 한다.

var nameoffunction = (params) => {				
 // code here			
}

//-----------------------------------------------------------------------

var ScoreCard = function () {
    this.score = 0;

    this.getScore = function () {
        setTimeout(function () {
            console.log(this.score);    // gives undefined.    
        }, 1000);
    }    
}

var a = new ScoreCard();
a.getScore();

//------------------------------------------------------------------------
var ScoreCard = function () {
    this.score = 0;

    this.getScore = function () {
        setTimeout(()=>{
            console.log(this.score);   // you get  0
        }, 1000);
    }    
}

var a = new ScoreCard();
a.getScore();

모듈 : 기본적으로 외부에서 접근 불가, export시켜준 Entity(변수, 클래스, 인터페이스, 함수 등)에 대해서만 접근허용

각 스크립트 파일에 선언되어 있는 전역변수나 함수의 충돌을 피하기 위해 사용한다.

export  nameofthevariable or class name or interface name etc

//To import above variable or class name or interface you have to use import as shown below:

Import {nameof thevariable or class name or interfacename} from "file path here without.ts"

//-----------------------------------------------------------------------------

// test1.ts
export let age: number = 25;

// test2.ts
import { age } from "./test1"
let new_age :number = age;

//-----------------------------------------------------------------------------

//Customer.ts
class Customer {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    getName(): string {
        return this.name;
    }
}

export = Customer;

//testCustomer.ts
import Customer = require("./Customer");

let a = new Customer("Harry", 30);
alert(a.getName());

모듈컴파일

tsc --module commonjs testCustomer.ts

네임스페이스 : Namespace

// testnamespace.ts
namespace StudentSetup {

    export interface StudDetails {
        name: string;
        age: number;
    }

    export function addSpace(str) { // will add space to the string given
        return str.split("").join(" ");
    }

    export class Student implements StudDetails {
        name: string;
        age: number;

        constructor(studentdetails: StudDetails) {
            this.name = studentdetails.name;
            this.age = studentdetails.age;
        }

        getName(): string {
            return this.name;
        }
    }
}


// testStudentSetup.ts
let a = new StudentSetup.Student({ name: "Harry", age: 20 });

console.log("The name is :" + StudentSetup.addSpace(a.getName()));


// 하나로 합쳐서 컴파일하기
tsc --outFile namespace.js testnamespace.ts testStudentSetup.ts

3th-party 자바스크립트 라이브러리 사용

선언: declare module moduleName { }
저장: filename.d.ts
사용: /// <reference path="filename.d.ts"/>

// testString.js (3rd-party 자바스크립트 라이브러리)
var StringChecks = {
    isString: function (str) {
        return typeof str === "string";
    },

    convertToUpperCase: function (str) {
        return str.toUpperCase();
    },

    convertToLowerCase: function (str) {
        return str.toLowerCase();
    },

    convertToStringBold: function (str) {
        return str.bold();
    }
};


// Ambient Module 생성
// tstring.d.ts
declare module TestString {

    export interface StringsFunc {
        isString(str: string): boolean;
        convertToUpperCase(str: string): string;
        convertToLowerCase(str: string): string;
        convertToStringBold(str: string): string;
    }
}

declare var StringChecks: TestString.StringsFunc;

// Ambient Module 사용
// test.ts
/// <reference path="tstring.d.ts"/>
let str1 = StringChecks.isString("Hello World");
console.log(str1);
let str2 = StringChecks.convertToUpperCase("hello world");
console.log(str2);
let str3 = StringChecks.convertToLowerCase("HELLO");
console.log(str3);
let str4 = StringChecks.convertToStringBold("Hello World");
console.log(str4);

// Html에서 사용
<html>			
<head>			
    <title>Test Typescript Ambient</title>			
    <script src="/testStrings.js"></script>			
    <script src="/test.js"></script>			
</head>			
<body>			
</body>			
</html>

쿠키 다루기 : Cookie