틀린 예시)
let user:object;
user = {
name: 'xx',
age: 30
}
console.log(user.name) // object에는 name 이라는 속성이 없으므로 오류
property를 정해서 객체를 표현하고싶을 때 사용
interface 사용 예시
type Score = 'A' | 'B' | 'C' | 'F'; // 문자열 literal type, 범위가 정해진 type을 생성
interface User{
name: string;
age: number;
gender? : string // ?는 optional 표시
readonly birthYear : number; // readonly는 읽기전용 속성이라는 뜻 (수정 불가)
[grade: number] : Score; // key는 number, value는 Score인 property를 여러개 받을 수 있다는 의미
}
let user : User = {
name: 'xx',
age: 30
birthYear: 2000 // 최초 생성시에만 할당 가능
1 : 'A',
2 : 'B'
}
user.age = 10; // age 수정
user.gender = "male" // gender 추가
ex1)
interface Add {
(num1:number, num2:number): number;
}
const add : Add = function(x, y){
return x + y;
}
add(10,20);
ex2)
interface IsAdult {
(age:number):boolean;
}
const a:IsAdult = (age) => {
return age > 19;
}
a(33); // true;
interface Car {
color: string;
wheels: number;
start(): void;
}
class Bmw implements Car {
// color: "red",
color;
wheels: 4;
start(){
console.log('go..');
}
constructor(c:string){ // 생성될 때(함수 호출시) 색상을 입력 받기
this.color = c;
}
}
const b = new Bmw('green')
console.log(b) // Bmw: {
"wheels": 4,
"color": "green"
}
b.start(); // "go.."
interface Benz extends Car { // Car가 가지고 있던 속성들을 그대로 가지게 됨
door: number; // 속성들을 추가로 정의
stop(): void;
}
const benz : Benz = {
door : 5;
stop(){
console.log('stop');
}
color : 'black' // 기존 속성들도 입력이 필요함
wheels: 4;
start(){
console.log('go..');
}
}
interface Car {
color: string;
wheels: number;
start(): void;
}
interface Toy {
name : string;
}
interface ToyCar extends Car, Toy {
price: number; // ToyCar은 Car 속성, Toy 속성, price 까지 모두 필요
}
function add(num1:number, num2:number): number {
return num1 + num2;
}
function isAdult(age: number): boolean{
return age > 19;
}
아무것도 return 하지 않을 때는 함수 type을 void라고 할 것 (ex. console만 찍는 함수)
선택적 매개변수: 함수의 매개변수를 optional로 지정
예시)
function hello(name?:string) { // ?는 optional의 표시
return `Hello, ${name || "world"}`; // name이 있으면 쓰고 없으면 'world'를 사용
}
== (같은 표현)
function hello2(name = "world") {
return `Hello, ${name}`;
}
const result = hello();
const result2= hello("Sam");
예시2)
function hello(name: string,age?: number):string { // 선택적 매개변수는 필수적 매개변수보다 뒤에 써줌
if (age !== undefined) {
return `Hello, ${name}. You are ${age}.`;
} else {
return `Hello, ${name}`;
}
}
// 선택적 매개변수를 앞에 사용하고 싶으면..
function hello(age: number | undefined, name: string): string {
...
}
console.log(hello(undefined, "Sam"));
console.log(hello("Sam"));
예시3)
function add(...nums: number[]) {
return nums.reduce((result,num) => result + num, 0);
}
add(1, 2, 3);
interface User {
name: string;
}
const Sam: User = {name: 'Sam'}
function showName(this:User){ // this의 타입을 정할 때는 함수의 첫번째 매개변수 자리에 입력
console.log(this.name) // this는 사용방법이 여러가지가 있음
}
const a = showName.bind(Sam); // 여기서는 bind를 이용하여 this를 Sam 객체로 감지
a();
*매개변수가 있을 때는
function showName(this:User, age:number, gender: 'm'|'f'){ // this의 타입을 정할 때는 함수의 첫번째 매개변수 자리에 입력
console.log(this.name, age, gender)
}
const a = showName.bind(Sam);
a(30, 'm'); // this 다음부터 매개변수를 전달
interface User {
name:string;
age:number;
}
// 오버로드 작성
function join(name:string, age: string) :string;
function join(name:string, age: number) :User;
function join(name: string, age: number | string): User | string {
if (typeof age === "number") {
return {
name,
age,
};
} else {
return "나이는 숫자로 입력하시오"
}
}
// 매개변수(age)의 type에 따라서 반환값이 달라짐
const sam: User = join("Sam", 30);
const jane: string = join("Jane", "30");
// 에러: 왜냐면 sam과 jane의 type(User, string)을 확신하지 못함
=> 이럴 때 함수 오버로드를 사용