선언한 타입에 맞지 않는 값을 할당하면 컴파일 시점에 에러가 발생한다. 타입 선언은 강력한 타입 체크를 가능하게 하여 문법 헤어나 타입과 일치하지 않는 값의 할당등 기본적인 오류를 런타임 이전에 검출한다.
const str: string = 'STRING' // 문자열 : string
const num: number = 123 // 숫자 : Number
const boo: boolean = true // 불린 : Boolean
const obj: { name: string, age: number } = {
name:'ujin',
age: 21
}
const obj: { name: string, age: number } = {
name:'ujin',
age: false,//Error
email: 'hong@naver.com' // Error
}
const obj: object = { //Property 'num' does not exist on type 'object'.
str: 'str',
num: 123,
child: {
str: 'str',
num: '123'
}
}
=============================================
const obj: {
str: string,
num: number,
child: {
str: string,
num: number,
}
} = {
str: 'str',
num: 123,
child: {
str: 'str',
num: 123,
}
}
console.log(obj.child)
function foo(num: number, str: string){
return num + str
}
foo(123, 'str') // 매개변수와 반환 값의 타입은 같아야 한다
function foo(num: number, str: string):void{ // 반환값의 타입으로 void를 넣으면
return num + str // 에러가 난다
}
foo(123, 'str')
function foo(num1: number, num2: string):number{
return num1 + Number(num2)
}
foo(123, '123')
const foo = (str1: string, str2: string):string => {
return str1 + '' + str2
}
foo('hello', 'world')
const foo = (obj: {str1: string, str2: string}) => { // 객체 타입
return obj.str1 + '' + obj.str2
}
foo({ str1: 'hello', str2: 'world' })
const strArr: **string[]** = ['str', 'str2', 'str3']
const strArr: **Array<string>** = ['str', 'str2', 'str3']
유니언 타입(다중 타입)
의 문자열과 숫자를 동시에 가지는 배열도 선언할 수 있다.
const array: (string | number)[] = ['apple', 3, 2, 'watermelon'];
const array: Array<string | number> = ['apple', 3, 2, 'watermelon'];
배열이 가지는 항목의 값을 단언할 수 없다면 any를 사용할 수 있다.
let someArr: any[] = [0, 1, {}, [], 'str', false];
인터페이스나 커스텀 타입을 사용할 수도 있다.
interface Foo {
name: string;
age: number;
isVaild: boolean;
}
const array: Foo[] = [
{
name:'hong',
age: 21,
isVaild: true,
},
{
name:'yu',
age: 20,
isVaild: false,
}
]
let letString = 'Hello' // type:string
letString
const constString = 'Hello' // 'Hello'
constString
let letNumber = 123 // type:number
letNumber
const constNumber = 123 // 123
constNumber
// const만 특정 값을 지칭하고 let은 type를 지정한다
// let은 언제든지 **재할당이 가능**하기에 **string으로 유지**한다
// const는 **재할당이 불가능**하기에 **리터럴값으로 유지**한다
const arr: string[] = ['a', 'b', '0'**, true, function foo() {}**]
// -> 진한 글씨처럼 불안정한 배열을 쓰기 위해서
const tuple: [number, string] = [1, 'a'] // declare const tuple: [number, string]
const typle2: [number, ...string[]] = [0, 'A', 'B', false] // 에러가 난다. -> 이 모습을 보면 배열 타입의 길이를 조절한다는 것을 알 수 있다
const type: undefined = undefined;
const type2: null = null;
function foo(word: string) { // return 타입을 따로 지정하지 않아도
// declare function foo(word: string): **string | null이 지정된다**
if(word === 'world') {
return 'hello' + word
}
return null
}
const any: any = 123;
any = 'play game';
any = {};
any = null;
여러 값을 포함하는 배열을 나타낼 때 사용할 수도 있다.
const arr: any[] = [1, true, 'typescript'];
const u: unknown = 123;
const test1: number = u // 알 수 없는 타입(unknown)은 모든 타입(any)을 제외한 다른 타입에 할당할 수 없다
const test2: number = u as number; // 타입을 단언하면 할당할 수 있다
const test3: any = u; // any와 unknown은 서로 할당할 수 있다