typescript

오미희·2022년 1월 5일
0

Typescript

마이크로소프트 사에서 오픈소스로 공개한 compile-to-javascript language.
브라우저는 html, css, javascript만 해석가능하므로 typescript 사용을 위해서는 typescript로 작성한 파일을 javascript로 컴파일해야한다.

  • typescript 확장자명 : .ts
  • 동적타이핑만을 지원하는 자바스크립트와 달리 타입스크립트는 정적타이핑과 동적타이핑 모두 지원.

✔️ 동적타이핑

변수 사용 전 타입을 할당하지 않아도 실행됨. 즉 런타임 도중 변수타입을 취하게 됨.

✔️ 정적타이핑

변수를 사용하기 전 반드시 타입을 할당

즉 타입스크립트 사용을 위해서는 타입스크립트를 자바스크립트로 변환시켜주는 컴파일이 필요.

예시)
function getFindPrice(price:number, discount:number){
	return price-priec/discount
}
console.log(getFindPrice(100,10)
console.log(getFindPrice(100,"10%")// 변수에 할당해준 타입과 달라서 오류남.

1. 실행 환경 세팅

⭐ node.js에서 타입스크립트 사용 ⭐

  1. npm install typescript
  2. npm install @types/node
  3. tsconfig.json작성
    > npx tsc --init tsconfig.json 파일 생성해줌
// 예시
// 옵션 내용은 달라질 수 있음
{
    "compilerOptions": {
      "noImplicitAny": false,
      "noEmitOnError": true,
      "removeComments": false,
      "sourceMap": false,
      "target": "es5",
      "outDir": "jsfiles"
    },
    "include": [
      "tsfiles/**/*"
    ]
  }
  1. tsfiles폴더와 jsfiles폴더 생성
  2. tsfiles폴더에 test.ts파일 생성
  3. 터미널에 npx tsc 입력
    // 위의 명령어 입력하여 tsfiles폴더의 ts파일들이 컴파일되어 jsfiles에 js파일들로 생성된다.

2. 기본 타입

2-1. 기본 타입 표기
변수선언:타입
let name:string;
let age:number;

2-2. 주요 타입
string
boolean true 혹은 false
number
null
undefined
Symbol  Symbol 생성자를 호출해 생성된 고유값
Array
Any  모든 타입 허용하므로 가능한 사용하지 말아야 한다.
Void 값 없음, 보통 함수 리턴에서 많이 쓰임.
Never
Enum
Tuple
** Primitive Type
: 실제 값을 저장하는 자료형
** literal
: 값자체가 변하지 않는 값

값이 없음

undefined : 값이 할당되지 않은 변수 or 값을 반환하지 않는 함수
null : 값이 null임을 명시적으로 선언한 것.
ex) let value = null;
함수 본문에 return 값이 없는 경우 undefined를 반환 void타입 선언이 이를 방지해줌.

- number
let decinal: number = 6  // 10 진수 literal
let hex : number = 0xf00d // 16 진수 literal
let binary : number = ob1010 // 2진수 literal
let octal : number = 0o744  // 8진수 literal
- void
타입이 없는 상태
함수의 리턴이 없을 때 사용.
function myName(name:string){
	console.log(`내 이름은${name}`)
}
// 함수를 실행하지만 반환하는 값 없이 콘솔만 출력 
// 이때에 voidTest()는 오류 반환값없이 타입이 단순히 string이므로.

function voidname(name:string)void{
	console.log(`내이름은${name}`)
}
예제1)
function Tax(state:string,income:number,dependents:number):number|undefined{
    if(state === "NY"){
        return income * 0.06 - dependents
    }else if(state === "NJ"){
        return income * 0.05 - dependents
    }
}

let value:number|undefined = Tax("Ny",10000,1);

- Array
사용법
L Array<타입>
L 타입[]
ex)
interface Person {
	name: string;
    age: number
}
const p:Person = {
	name:'mark',
    age:35
}
Person[]
Array<Person>

- Tuple
배열인데 타입이 한가지가 아닌 경우
const tu:[number, string] = [0,"one"];

- Enum
ex)
enum color {Red, Green, Blue}
let c: Color = color.Green;

enum olor {Red=1, Green, Blue}
let c: color = color.Green

enum color {Red = 1, Green = 2, Blue = 4}
let c: color = color.Green

eumn color {Red = 1, Green, Blue}
let colorName: string =. Color[2]  // Green

- Symbol
프리미티브한 타입의 값을 담아서 사용
고유하고 수정불가능한 값으로 만들어줌.

3. var, let, const

var

  • 변수의 유효 범위 : 함수 스코프
  • 호이스팅됨
  • 재선언 가능
    let, const
  • 변수의 유효 범위 : 블록 스코프
  • 호이스팅안됨
  • 재선언 불가

현재 var는 거의 사용하지 않음

4. interface

const person: {name:string,age:number} = {
	name: 'Mark',
    age:27
};
// 위의 코드를 interface로 하면

interface Person{
	name: string;
    age?: number;
    // 물음표를 불여주면 옵션이 되어 해당 값이 없어도 됨
}
const person:Person = {
	name:'Mark',
    //age:27 
}

------------------------------------------------
function hello(p:Person):void{
	console.log(`안녕하세요 ${p.name}입니다.`)
}
------------------------------------------------

--- indexable type ---

indexable타입의 index는 index이거나 number만 가능
interface Person2 {
	name : string;
    [index: string]:string
}
const person2:Person = {
	name: 'Mark'
}
person2.anybody = 'Anna' 

interface Person3 {
	[index:number]:string
    //[index:number] : Person
}
const p2: Person3 = {};
p2[0] = 'hi';
p2[3] = 'hello';

--- interface 안의 함수 ---

interface Person {
	name:string;
    hello():void;
    //say():string;
}
const person:Person = {
	name:'Mark',
    hello: function(){
    	...
    }
    //say():string => {
    //	return 'say';
    //}
}

--- class implements interface ---

ex)
interface Iperson {
	name:string;
    age:number;
    hello(): void;
}

class Person implements Iperson {
	name:string;
    constructor(name:string){
    	this.name = name
    }
    hello(): void {
    	console.log('hello')
    }
    public hi():void {
    	console.lgo('hi')
    }
}

const person: Iperson = new Person('mihee');
// interface에 명시된 것만 구현.

--- interface extends interface ---

interface Person {
	name:string;
    age?:number;
}
interface Korean extends Person {
	city:string;
}
const k:Korean = {
	name:'이웅재',
    city:'서울'
}

--- function interface ---

interface HelloPerson {
	{name:string, age?:number}:void;
}

let helloPerson:HelloPerson = function (name:string) {
	console.log('안녕하세요')
};
helloPerson('mark')

// 함수의 타입 체크는 할당할 때가 아니라 사용할 때 한다.

5. class

클래스의 접근제어자는 public이 디폴트이다.
클래스의 프로퍼티가 정의되고 값을 할당하지 않으면 undefined로 나온다.
그러므로 임의로 null을 할당해주는 것이 좋음.

  • private으로 설정된 프로퍼티는 .으로 접근 불가
  • private이 붙은 변수나 함수는 _를 앞에 붙여서 사용한다.
class Person {
	//name:string;
    //age:number
	name:string = null;
    age:number = null;
    constructor(name:string){
    
    }
}
const person:Person = new Person();
//console.log(person)  //person{}
person.age = 27;

--- 접근제어자 ---

L public
모든 내부 및 외부 클래스에서 접근 가능.
타입스크립트는 기본적으로 모든 클래스 멤버의 접근 권한이 public이다.
L private
해당 클래스 내에서만 접근 가능, 즉 자식 클래스 등이 접근할 수 없음
L protected
동일 패키지에 속하는 클래스와 서브 클래스 관계일 경우에만 접근 가능. 즉 서브클래스 즉 자식클래스는 접근 가능
// 상속을 받은 자식 클래스에서 부모 클래서에 this를 통해 접근하려면, 생성자에서 super(); 를 명시해주어야 함
class Parent {
	private privateProp:string;
  	protected protectedProp:string;
  
  	constructor(){
    
    }
}
class Child extends Parent {
	constructor() {
    	super();
      
      	this.protectedProp = 'protected'  
    }
}

--- 클래스와 함수 ---
  
class Person {
	protected _name:string = 'mihee';
    private _age:number = null;
  
  constructor(name:string, age:number){
  	this._name = name;
    this._age = age;
  }
  hello():void {
  	console.log(this._name)
  }
}

const person:Person = new Person('mihee',27);
person.hello();

--- 클래스와 상속 ---
  
 class Person {
 	constructor(protected _name:string, protected _age:number){
    
    }
   print():void {
   	console.log(this._name)
   }
   private printAge():void{
   	console.log(this._age)
   }
 }

class Child extends Person {
  constructor(){
  	super('mihee oh',5)
  }
}

const child:Child = new Child();
child.print();

--- 클래스와 getter,setter ---
  
비공개로 설정할 필요가 있는 속성을 private으로 설정 후 해당 속성에 대한 접근은 get() set() 함수를 사용하요 속성 정의.
 
class Plant {
	private _species:string|null =null;
    
    //get()
    get species():string{
    	return this._species;
    }
    
    //set()
    set species(values:string){
    	if(value.length > 3) {this._species = value; }
    }
}

 /* --- 인스턴스 생성 --- */
 let plant = new Plant();
 console.log(plant.sepecies);  // null
 plant.species = '줄기';
 console.log(plant.species);   // null
 plant.species = '푸른식물';
 console.log(plant.species)    // 푸른식물

--- 클래스와 static 프로퍼티 ==> 클래스 멤버 변수 ---
  
class Person {
	
}
///////10강 5분



 


6. Generic

7. iterator

8. Decorator


커스텀 타입

  • type //새로운 타입을 선언
  • interface
  • enum
-type
type email = 'string'
type phone = 'number'
// email의 타압은 string으로
// phone의 타입은 number로 선언
type Person = {    
    name:string;
    connect:phone;
    ?e_connect:email;
}

let person:Person={
    name:'mihee',
    connect:01011112222,
    //e_connect:'algml9603@gmail.com'
}
// 타입 선언시 속성key앞에 ?를 붙여주면 해당값은 옵션값으로 값을 주지 않아도 됨.

readonly 제한자

// 클래스 생성자 내부 등에 프로퍼티를 초기화하는 경우 그 값이 바뀌지 않아야 하는 경우.


😀 기타 개념

  • 싱글톤
    객체 지향 언어에서 단 하나의 인스턴스를 생성하는 디자인 패턴
  • private 생성자가 있는 경우 new 키워드로 새로운 인스턴스 생성할 수 없다.
  • 자식클래스에서 생성자를 선언하지 않은 경우 부모의 생성자가 자동 호출되며,
    자식클래스와 부모클래스 모두에 생성자를 선언한 경우에는 super()로 부모클래스의 생성자를 호출해야함
  • 다형성(polymorphism)
    상속을 통해 기능을 확장하거나 변경하는 것.


static

클래스를 통해 인스턴스 생성할 필요 없이 클래스의 속성 또는 메서드를 사용하려 하는 경우 사용

class Mathmatics {
  // 스테틱 속성
  static PI:number = Math.PI;
  
  // 스테틱 메서드
  static calcCircumference(radius:number) :number {
    return this.PI * radius * 2;
  }
  
  static calcCircleWidth(radius:number):number{
    return this.PI * Math.pow(radius, 2)
  }
}

let radius = 4; 

console.log('PI(원주율) = ', Mathmatics.PI);
console.log(`반지름이 ${radius}인 원의 넓이: πr² = `, Mathmatics.calcCircleWidth(radius));
console.log(`반지름이 ${radius}인 원의 둘레: 2πr = `, Mathmatics.calcCircumference(radius));

abstract

타입스크립트 참고 사이트

profile
안녕하세요

0개의 댓글