타입스크립트는 자바스크립트에 타입을 부여한 언어이다.
자바스크립트에서 확장된 언어이다.

TypeScript에서는 변수를 만들어 값을 할당하면 처음 할당된 값의 형식에 따라 그 변수의 형식이 지정되게 된다. 이를 Type Annotation이라고 한다.
<종류>
<예시>
const str: string = 'STRING'
const num: number = 123
const bool: boolean = true
const big: bigint = 100n
const obj: object = {
str: 'str',
num: 123,
child: {
str: 'str',
num: 123,
}
}
const obj2: {
str: string,
num: number,
child: {
str: string,
num: number,
}} = {
str: 'str',
num: 123,
child: {
str: 'str',
num: 123,
}
}
console.log(obj2.str)
/**
* Function Type
*
* //매개변수를 받고 리턴을 하게된다 두가지타입이 필요하다 그래서 타입을 2개 지정해야한다.
*
*
* 1. 매개변수
* 2. 반환
* void는 반환하지 않는다라는 뜻
*/
function func(num: number, str: string): string {
return num + str
}
func(123, 'str')
function func2(num1: number, num2: string) {
return num1 + Number(num2)
}
//반환 타입은 타입추론이 잘되는 편이다
func2(123, '123')
function func3(num1: number, num2: string): void {
console.log(num1 + num2)
}
func3(123, '123')
const func4 = (str1: string, str2: string) => {
return str1 + ' ' + str2
}
//반환 타입은 타입추론이 잘되는 편이다
func4('hello', 'world')
const func5 = (obj: {str1: string, str2: string}) => {
return obj.str1 + ' ' + obj.str2
}
func5({str1: 'hello', str2:'world'})
<예시>
const strArr: string[] = ['str', 'str2', 'str3'];
const strArr2: Array<string> = ['str', 'str2', 'str3'];
const numArr: Array<number> = [1, 2, 3];
const boolArr: boolean[] = [false, true, false, true];
strArr.push(1) // error : string으로 넣어야한다.
numArr.push('str') // error : number로 넣어야한다.
boolArr.push(false)
const arr = ['str', 123, false];
/**
* Literal Type
*/
let letString = 'Hello'
letString = letString + ' World'
console.log(letString)
const constString = 'Hello'
constString
let letNumber = 123
letNumber = letNumber + 123
console.log(letNumber)
const constNumber = 123
constNumber
/**
* Tuple Type
*
* - 길이 고정 & 인덱스 타입이 고정
* - 여러 다른 타입으로 이루어진 배열을 안전하게 관리
* - 배열 타입의 길이 조절
*/
const arr: string[] = ['A', 'B', 'C']
const tuple: [number, string] = [1, 'A']
const tuple0: (string | number)[] = [1, 'A']
const tuple2: [number, ...string[]] = [0, 'A', 'B']
/**
* undefined & null
*
* JavaScript에서와 마찬가지로
* 고유의 특별한 타입으로 인정한다.
*
* 이외에 void, never와 같이 더 세밀한 타입도 제공
*
* strictNullChecks가 핵심
*/
const nu: null = null;
const un: undefined = undefined;
function sayHello(word: string) {
if (word === 'world') {
return 'hello' + word
}
return null
}
function log(message: string | number) {
console.log(message)
}
/**
* any
*
* 모든 값(타입)의 집합
* 사용하지 말자
*
* noImplicitAny or strict 옵션 true 권장
*/
function func(anyParam) {
anyParam.trim()
}
func([1,2,3])
/**
* unknown
*
* 새로운 최상위 타입
* any처럼 모든 값을 허용하지만 상대적으로 엄격하다.
* TS에서 unknown으로 추론하는 경우는 없으니 개발자가 직접 명시해야함
* assertion 혹은 타입 가드와 함께 사용한다.
*/
let num: unknown = 99;
if (typeof num === 'string') {
num.trim();
}
// (num as string).trim();
// function func(x: unknown) {
// let val1: any = x;
// let val2: unknown = x;
// let val3: string = x;
// let val4: boolean = x;
// let val5: number = x;
// let val6: string[] = x;
// let val7: {} = x;
// }