
let a: string = 'hello';
: 변수를 선언할 때 변수에 할당할 값의 타입에 따라 미리 타입을 선언하고, 그 타입에 맞는 값을 할당 하는 것 ex) C, JAVA
var a;
console.log(typeof a); // undefined
a = null;
console.log(typeof a); // object
a = {};
console.log(typeof a); // object
a = 3;
console.log(typeof a); // number
a = 3.14;
console.log(typeof a); // number
a = "Hi there";
console.log(typeof a); // string
a = true;
console.log(typeof a); // boolean
: 타입 선언을 생략하면 값이 할당되는 과정에서 동적으로 타입 결정
let a = 123; // a는 number 타입
타입을 선언하지는 않았으나 타입 추론에 의해 변수의 타입이 결정된다.
타입 선언을 하지 않고 값을 할당하지도 않아서 타입 추론이 어려우면 any 타입이 된다.
any는 재할당이 가능하다 = JS의 var 처럼
하지만, 사용하지 않는 것이 좋다
: 기존의 타입에서 다른 타입으로 타입 캐스팅 하려면 as 키워드 or <> 연산자 사용
const $input = document.querySelector('input["type="text"]');
// => $input: Element | null
const val = $input.value;
// TS2339: Property 'value' does not exist on type 'Element'.
$input.value를 실행하면 Element 또는 null 타입에 value가 존재하지 않으므로 컴파일 에러가 발생 -> 타입 캐스팅 필요
// as
const $input = document.querySelector('input["type="text"]') as HTMLInputElement;
const val = $input.value;
// <>
const $input = <HTMLInputElement>document.querySelector('input["type="text"]');
const val = $input.value;