const a: string = '5';
const b: string = 'world';
const c: string = "hello";
const str:string = `hello ${b}`; // hello world
function add(x: string, y: string): string {
return x + y
}
const result = add('2','5')
console.log(result) // 25
const b: number = 5;
let decimal: number = 6; // 10진법
let hex: number = 0xf00d; // 16진법
let binary: number = 0b1010; // 2진법
let octal: number = 0o744; //8진법
function add(x: number, y: number): number {
return x + y
}
const result = add(2,5)
console.log(result) // 7
❗부동 소수란, 컴퓨터에서 2진수로 표현할 수 없는 소수를 근사한 값으로 변환하는 방법으로, 이름 그대로 소수점을 고정하지 않는 (floating point) 방식이다!
const c: boolean = true;
const d: undefined = undefined;
const c: null = null;
null과 undefined은 다른 모든 타입의 하위타입으로 이 둘은 여러 타입에 할당할 수 있다는 걸 의미한다. * tsconfig.json에서 strick 모드가 아닐 경우에만 가능하다.
const c: string = null; // error: 'null' 형식은 'string' 형식에 할당할 수 없다.
if(!c) {
c = 'hello'
}
❗컴파일 옵션인 --stricks 이나 --strictNullChecks를 사용하면, null과 undefined는 오직 any와 각자 자신들 타입에만 할당 가능하게 된다. (예외적으로 undefined는 void에 할당 가능합)
이 옵션은 불특정한 많은 일반적인 에러를 방지하는 데 도움을 주니, 가능한 경우 --strictNullChecks를 사용할 것을 권장하는 편이다.
const arr: string[] = ['123', '456']
const arr2: Array<number> = [123, 456]
const obj: { lat: number, lon: number } = { lat: 37.5, lon: 127.5 };
튜플은 길이가 고정된 배열이라는 뜻이다. 일반적으로 배열들은 길이를 마음대로 늘릴 수 있다. 근데 튜플은 길이가 고정되어 있어서 [] 배열을 먼저 만들어주고 그다음에 [number,number,string] 이렇게 고정되게 하나하나 타이핑 해주는 방식이다.
const arr3: [number,number,string] = [123,456,'hello']
arr3[3] = 'world' // 이렇게 네 번째 자리에 넣으려고 하면 error남.
arr3.push('world') // 웃긴 게 이렇게 push로 하면 error가 안 남.
const arr3: readonly [number,number,string] = [123,456,'hello']
출처