Type Inference

홍범선·2023년 10월 20일
0

타입스크립트

목록 보기
5/34
let stringType = 'string';
let booleanType = true;
let numberType = 30;

Js에서는 단순히 변수에 값을 저장하는 것이다.
TS는 다르다

마우스를 올리면 Type이 자동적으로 설정되는 것을 볼 수 있다.
let stringType:string = 'string'
let booleanType:boolean = true;를 하지않아도
TS가 타입을 추론해서 설정을 해준다.

booleanType = false;
//booleanType = 'false' // 초기화 할 때 boolean으로 설정했기 때문에 에러

false는 불리안 타입이기 때문에 에러가 발생하지 않는다.
반면에 'false'는 string 타입이기 때문에 에러가 발생한다.
자동적으로 타입이 설정된 것을 확인 할 수 있다.

const constStringType = 'const string';
const constBooleanType = true; // const를 사용하면 구체적으로 사용된다.

const로 값을 설정하면 어떻게 될까?

let과는 다르게 constBooleanType이 true로 구체적으로 지정된 것을 볼 수 있다.
constBooleanType은 true만 쓸 수 있게 되는 것이다.

let yuJin = {
  name: '안유진',
  age:2003
}

const yuJin2 = {
  name: '안유진',
  age:2003
} 

yuJin2.name = '코드팩토리';

객체에서 const를 사용하면 변경할 수 없게 만들 수 있지 않을 까 했지만 변경할 수 있다.
객체에서 const를 사용하려면 다음과 같이 해야한다.

const yuJin3 = {
  name: '안유진' as const,
  age:2003 as const,
}

//yuJin3.name='코드팩토리';

객체의 이름을 바꾸려고 하면 에러가 발생한다.
왜냐하면 name은 구체적으로 '안유진'이 와야하고 age는 2003이 와야한다고 명시했기 때문이다.

let numbers = [1,2,3,4,5];
let numbersAndString = [1,2,3,'4','5','6'];

numbers.push(6);
// numbers.push('6'); => error

배열도 마찬가지다.

numbers 배열은 TS에서 자동적으로 number[]의 타입을 설정한 것을 볼 수 있다.
그래서 6을 push하면 number타입이기 때문에 작동하지만
'6'을 push하면 string타입이기 때문에 에러가 발생한다.

numbersAndString 배열은 number와 string이 썪여 있다.
TS는 타입을 number|string타입으로 설정한다.
numbersAndString.push(null) 을 할 경우 에러가 발생한다.

const number = numbers[0];
const nos = numbersAndString[0];
const nos2 = numbersAndString[6]; // 길이가 넘어도 버그 체크가 안됨 undefined됨
//tuple
const twoNumbers = [1, 3] as const;

// twoNumbers[0] = 10; => 에러
// twoNumbers.push(100); => 에러
const first = twoNumbers[0];
//const first2 = twoNumbers[3]; //길이가 넘으면 바로 체크가 됨 에러

하지만 numberAndString은 길이가 넘는 것은 체크를 하지 않는다. 이럴 때 구체적으로 사용하려면 tuple을 사용해야 한다.

profile
알고리즘 정리 블로그입니다.

0개의 댓글