jeongsa123 / TIL

0 stars 0 forks source link

타입스크립트 정리 #16

Open jeongsa123 opened 1 year ago

jeongsa123 commented 1 year ago

1. 기본타입

string: 문자열 number: 숫자타입 boolean: 명제(참, 거짓) number[]: 숫자배열 == Array 👍 string[] : 문자배열 == Array 👍

😋 타입스크립트의 장점 타입을 미리 정의하여 오류를 런타임에 오류를 알수 있음

2. 튜플

let b : [string, number];  // =>튜플안에 0번째 값은 문자 1번째 값은 숫자만 가능

tolowerCase(); // 문자열을 소문자로 변환된 값을 리턴함

3. void, never

funtion sayHello():void{
      //반환값이 없는 함수 void 로 선언함
}

function infLoop():never{
     while(true){
              // 무한루프 함수는 never로 선언함
      }
}

3. enum

enum fruit{
         apple,
         orange,
         grape
}

enum은 열거형으로 다음과 같이 선언함 현재 아무값도 설정 안 했음으로 apple = 0 orange = 1 grape = 2 의 값이 할당됨 그리고 0 = apple 1 = orange 2 = grape 가 됨 만약 여기서

enum fruit{
         apple = 1,
         orange,
         grape
}

다음과 같이 선언하면 orange = 2 grape = 3 을 할당 받음

4. 객체

let user:object;
user ={
        name:"윤석"
        age:38
        sex:"남"
};
// user 라는 객체를 선언하고 user가 가지는 값을 서

5. 인터페이스

타입스크립트에서 인터페이스는 다음과 같은 범주에 대해 약속을 정의한다.

interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);

LabeledValue 이라는 인터페이스를 생성하고 그 인터페이스는 label이라는 속성을 가지고 label은 string이라는 타입을 가진다. printLabel이라는 함수의 labeledObj의 파라미터는 LabeledValue 인터페이스의 속성을 가진다. 여기서 만약 함수에 label이라는 속성 값이 없으면 에러가 난다. 이것을 해결하기 위해 옵션 속성을 설정한다.

interface personAge {
    name: string;
    age?: number;
}

function logAge(obj: personAge) {
    console.log(obj.name);
}

let person = {name:'Capt'};
logAge(person);

위의 코드는 personAge 라는 인터페이스에 age 속성을 옵셔널하게 처리한 것이다. 속성뒤에 "?"를 쓰면 해당 속성을 옵셔널 하게 처리할 수 있다. 반대로 읽기 전용 속성도 존재한다.

interface CraftBeer {
  readonly brand: string;
}

다음과 같이 readonly 로 처리하면 처음 생성할 때만 값을 할당하고 그 이후에는 변경할 수 없다. 배열도 마찬가지로 readonly 로 선언할 수 있다.

let arr: ReadonlyArray<number> = [1,2,3];
// 다음과 같이 처리하면 배열에 값을 할당하는 코드를 작성하면 에러가 난다.
//ex
arr.splice(0,1); // error
arr.push(4); // error
arr[0] = 100; // error
arr = [10, 20, 30]; // error

👍 타입스크립트는 인터페이스를 이용해 객체를 선언할 때 좀 더 엄밀한 속성 검사를 진행한다.

interface Person {
    name?: string;
}

function print(person: Person) {
    console.log(person.name);
}

let person = {nam : 'sol'};
// error: Object literal may only specify known properties, but 'nam' does not exist in type 'Person'. Did you mean to write 'name'?

위 코드를 보면 Person 인터페이스에는 name라고 선언되어 있지만 print() 함수에 인자로 넘기는 Person 객체에는 name이 선언되어 있어 오탈자 점검을 요하는 오류가 발생한다. 이것을 타입추론이라고 함 이러한 타입 추론을 무시하고 싶다면

 let person = {nam : 'sol'};
print(person as Person); // 결과: undefined

만약 인터페이스 내에 정의하지 않은 속성들을 추가로 사용하고 싶을 때는

interface Person {
    name?: string;
    [propName: string]: any;

}

함수타입

interface login {
  (username: string, password: string): boolean;
}
// login 인터페이스는 string 타입의 매개 변수를 받고 boolean 타입을 return 하는 함수만 정의가 가능

let loginUser: login = function(id: string, pw: string) {
    console.log('로그인 했습니다.');
    return true;
}

let logoutUser: login = function(id: string, pw: string) {
    console.log('로그아웃 했습니다.');
    return true;
}

클래스 타입

interface user {
  username: string; 
  print(name: string): void;
}

class Login implements user {
    username: string = 'sol';
    print(name: string) {
        console.log(name);
    }   
    constructor() {}
}
JeGwan commented 1 year ago

https://blog.logrocket.com/when-to-use-never-unknown-typescript/