let isDone: boolean = false;
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
"
나 '
를 문자열 데이터를 감싸는데 사용.let color: string = "blue";
color = 'red';
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.
I'll be ${ age + 1 } years old next month.`;
[]
을 쓰는 것.let list: number[] = [1, 2, 3];
Array<elemType>
let list: Array<number> = [1, 2, 3];
// 튜플 타입으로 선언
let x: [string, number];
// 초기화
x = ["hello", 10]; // 성공
// 잘못된 초기화
x = [10, "hello"]; // 오류
console.log(x[0].substring(1)); // 성공
console.log(x[1].substring(1)); // 오류, 'number'에는 'substring' 이 없습니다.
x[3] = "world"; // 오류, '[string, number]' 타입에는 프로퍼티 '3'이 없습니다.
console.log(x[5].toString()); // '[string, number]' 타입에는 프로퍼티 '5'가 없습니다.
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue} // 0 대신 1부터 시작해 번호를 매긴다.
let c: Color = Color.Green;
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
console.log(colorName); // 값이 2인 'Green'이 출력됩니다.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // 성공, 분명히 부울입니다.
let notSure: any = 4;
notSure.ifItExists(); // 성공, ifItExists 는 런타임엔 존재할 것입니다.
notSure.toFixed(); // 성공, toFixed는 존재합니다. (하지만 컴파일러는 검사하지 않음)
let prettySure: Object = 4;
prettySure.toFixed(); // 오류: 프로퍼티 'toFixed'는 'Object'에 존재하지 않습니다.
Object
- 객체 타입인 Object는 interface, class 의 상위 타입이다.
- http://daplus.net/typescript-any%EB%8C%80-object/
- 타입의 일부만 알고 전체는 알지 못할 때 유용, 여러 다른 타입이 섞인 배열을 다룰 수 있다.
let list: any[] = [1, true, "free"];
list[1] = 100;
### 1.8) Void
- 어떤 타입도 존재할 수 없음. (<-> any)
- 보통 함수에서 반환 값이 없을 때 반환 타입을 표현하기 위해 쓰인다.
### 1.9) Null and Undefined
- Undefined과 null 둘 다 각각 자신의 타입 이름으로 undefined , null로 사용합니다. void처럼 그 자체로 유용한 경우는 거의 없다.
```ts
// 이 밖에 이 변수들에 할당할 수 있는 값이 없습니다!
let u: undefined = undefined;
let n: null = null;
// never를 반환하는 함수는 함수의 마지막에 도달할 수 없다.
function error(message: string): never {
throw new Error(message);
}
// 반환 타입이 never로 추론된다.
function fail() {
return error("Something failed");
}
// never를 반환하는 함수는 함수의 마지막에 도달할 수 없다.
function infiniteLoop(): never {
while (true) {
}
}
declare function create(o: object | null): void;
create({ prop: 0 }); // 성공
create(null); // 성공
create(42); // 오류
create("string"); // 오류
create(false); // 오류
create(undefined); // 오류
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
기명 함수 vs 익명 함수
- 기명 함수: 브라우저가 런타임(RunTime) 이전에 선언 및 할당되는 함수
- 익명 함수: 브라우저가 런타임(RunTime)에 할당되는 함수
=> 함수가 호이스팅되고 안 되고 차이