number
string
boolean
undefined
: 보통 let age: number | undefined;
와 같이 쓰이고 단독으로 쓰이진 않는다.
null
: 거의 안쓰인다.
unknown
: any처럼 모든 타입을 받을 수 있지만 의미적으로 잘 모를때 씀
any
: 무엇이든 상관 없다. 거의 쓰이지 않(아야 하)고 외부 api나 다른 플랫폼에서 값을 받아와야 할 경우 쓰인다(고 엘리님이 말했지만 나는 종종 쓰게되는 것 같다..).
void
: return이 undefined인 경우
never
: throw new Error()
나 while(true)
처럼 함수가 리턴값이 없을 경우 사용
const fruits: string[] = ['토마토', '바나나'];
const scores: Array<string> = ['토마토', '바나나'];
function printArray(fruits: readonly string[]){}
readonly
를 사용하고 싶으면 string[]
으로 정의해야지 사용가능 type Text = string;
const name: Text = 'jongho';
const address: Text = 'korea';
type Num = number;
type Student = {
name: string;
age: number;
}
const student: Student = {
name: 'jongho',
age: 27,
}
type Name = 'jongho';
let jonghoName: Name;
jonghoName = 'jongho';
type Bool = true; // true값만 가질 수 있음
type Direction = 'left' | 'right' | 'up' | 'down';
function move(direction: Direction) {
console.log(direction)
}
// function: login -> success, fail
type SuccessState = {
response: {
body: string;
}
}
type FailState = {
reason: string;
}
type LoginState = SuccessState | FailState;
type SuccessState = {
result: 'success'; // discriminated union
response: {
body: string;
}
}
type FailState = {
result: 'fail'; // discriminated union
reason: string;
}
type LoginState = SuccessState | FailState;
function printLoginState(state: LoginState) {
if(state.result === 'success') {
console.log(state.response.body);
} else {
console.log(state.reason)
}
}
extends
)처럼 사용할 수 있다.type Student = {
name: string;
score: number;
}
type Worker = {
employeeId: number;
work: () => void;
}
function internWork(person: Student & Worker) { // 이 부분
console.log(person.name, person.employeeId, person.work);
}
internWork({
name: 'jongho',
score: 100,
employeeId: 12345,
work: () => {}
})
enum Days {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
console.log(Days.Monday); // 1
let day = Days.Sunday; // 7
day = 10; // 10
console.log(day); // 10
let text = 'hello'; // string으로 추론
function print(message = 'hello'/* string */ ) { // return이 void로 추론
console.log(message);
}
print('hello')
function jsStrFunc(): any {
return 2
}
const result = jsStrFunc();
console.log((result as string).length); // result가 string 타입이라고 강제해서 에러발생
console.log((<string>result).length); // result가 string 타입이라고 강제해서 에러발생
(result as string)
(<string>result)
동일<>
는 컴포넌트를 말하기 때문에, as
문법을 주로 사용한다고 한다.