본문 바로가기

Project/근육고양이

[근육고양이] TypeScript 객체와 인터페이스

728x90

객체와 인터페이스

객체

object타입은 number, string, boolean 타입의 값을 초기값으로 가질 수는 없지만 객체로 선언된 값들은 모두 가질 수 있다.

 

1
2
3
4
5
function ObjectExample() {
  let object_ex: object = { name'근육고양이', age: 13}
  object_ex = 1 //Type '1' is not assignable to type 'object'.
  object_ex = {hello: '안녕', introduce: '내 이름을 소개하지'name'난 근육고양이'}
}

 

위의 코드처럼 {}를 사용하여 객체로 만들어서 값을 넣어주면 object타입의 변수에 값을 넣어줄 수 있다.

 

인터페이스

interface는 객체의 타입을 정의하기 위해 사용된다. {}를 사용하여 속성을 정의한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface ICat {
  name: string
  age: number
}
 
function InterfaceExample() {
  let interface_ex_01: ICat = {name'인터페이스 고양이', age: 15}
 
  let interface_ex_02: ICat = {name'인터페이스 고양이'
  //Property 'age' is missing in type '{ name: string; }' but required in type 'ICat'.
 
  let interface_ex_03: ICat = {} 
  //Type '{}' is missing the following properties from type 'ICat': name, age
 
  let interface_ex_04: ICat = {name'인터페이스 고양이', age: 15, weight: 20
  //Type '{ name: string; age: number; weight: number; }' is not assignable to type 'ICat'.
}

 

name과 age 변수를 가지는 ICat 인터페이스를 만들었다. 변수들의 타입을 ICat으로 정의하여 생성해주면 ICat 인터페이스의 속성이 전부 있는 것들만 값을 유효하게 한다.

interface_ex_02는 age속성이 없어서 interface_ex_03은 아무런 속성이 없어서 interface_ex_04는 weight라는 정의되지 않는 속성이 있어서 오류가 발생하게 된다.

 

하지만 interface_ex_02의 경우처럼 이름 속성만 필요할 때가 있을 수도 있고 또는 interface_ex_04의 경우처럼 무게 속성이 추가로 필요한 경우가 생길 수도 있다. 이 문제를 해결할 수 있는 것이 선택 속성이다. 선택 속성은 인터페이스의 속성 이름 뒤에 ?를 붙이는 것으로 만들 수 있다.

 

1
2
3
4
5
interface ICat {
  name: string
  age?: number
  weight?: number
}

ICat 인터페이스를 위의 코드처럼 변경해준다면 interface_ex_02와 interface_ex_04는 더 이상 오류를 발생시키지 않을 것이다.

 

객체와 인터페이스 프로그래밍 언어에 있어서 많이 사용되는 문법이다. 자세하게 알고 있다면 코드 작성에 있어서 좋을 것 같다.

728x90