ㅇㅇㅈ Blog

프론트엔드 수행중

0%

Typescript-Interface

interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface Person1 {
// 컴파일 됐을때는 사라지게 된다
// 컴파일 타임에만 필요하다
// 컴파일 타임에 인터페이스를 이용해 관계를 규명해 체크해주는 역할
name: string
age: number
}

function hello1(person: Person1): void {
console.log(`안녕하세요 ${person.name}입니다`)
}

const p1: Person1 = {
name: 'Mark',
age: 39,
}
hello1(p1)

optional property (1)

1
2
3
4
5
6
7
8
9
10
11
12
13
interface Person2 {
name: string
age?: number
// 객체에 있을수도 있고 없을수도 있을때 ? 를 뒤에 붙인다
}

function hello2(person: Person2): void {
console.log(`안녕하세요 ${person.name}입니다 `)
}

hello2({ name: 'Mark', age: 39 })
hello2({ name: 'Anna' })

optional property (2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
interface Person3 {
name: string
age?: number
[index: string]: any
}

function hello3(person: Person3): void {
console.log(
`안녕하세요 ${person.name} ${person.systers} ${person.father}입니다`
)
}

const p31: Person3 = {
name: 'Mark',
age: 39,
}

const p32: Person3 = {
name: 'Anna',
systers: ['sung', 'chan'], // any 이기 때문에 들어 올 수 있다
}

const p33: Person3 = {
name: 'Bokdan',
father: p31, // any 이기 때문에 들어 올 수 있다
mother: p32, // any 이기 때문에 들어 올 수 있다
}

hello3(p31)
hello3(p32)
hello3(p33)

function in interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
interface Person4 {
name: string
age: number
hello(): void
}

const p41: Person4 = {
name: 'Mark',
age: 39,
hello: function (): void {
console.log(`안녕하세요! ${this.name} 입니다`)
},
}

const p42: Person4 = {
name: 'mark',
age: 39,
hello(this: Person4): void {
console.log(`안녕하세요! ${this.name}입니다`)
},
}

const p43: Person4 = {
name: 'Mark',
age: 39,
hello: (this: Person4): void => {
console.log(`안녕하세요! ${this.name}입니다`) // this는 글로벌을 가르킨다
},
}