TS.1-Interface

ㅎㅐ수·2021년 1월 3일
0


TS를 이제야 정리하다ㄴㅣ....🤭

Interface

인터페이스는 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용할 수 있다.
인터페이스는 여러가지 타입을 갖는 프로퍼티로 이루어진 새로운 타입을 정의하는 것과 유사하다. 인터페이스에 선언된 프로퍼티 또는 메소드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것이다.

변수와 인터페이스

// 인터페이스의 정의
interface Todo {
  id: number;
  content: string;
  completed: boolean;
}

//변수 todo의 타입으로 Todo 인터페이스를 선언하였다.
const todo: Todo;

//변수 todo는 Todo 인터페이스를 준수하여야 한다.
todo = {id:1, content: 'typescript', completed: false };

// 인터페이스의 정의
interface Todo {
  id: number;
  content: string;
  completed: boolean;
}

let todos: Todo[] = [];

// 파라미터 todo의 타입으로 Todo 인터페이스를 선언하였다.
function addTodo(todo: Todo) {
  todos = [...todos, todo];
}

// 파라미터 todo는 Todo 인터페이스를 준수하여야 한다.
const newTodo: Todo = { id: 1, content: 'typescript', completed: false };
addTodo(newTodo);
console.log(todos)
// [ { id: 1, content: 'typescript', completed: false } ]

함수와 인터페이스

인터페이스는 함수의 타입으로 사용할 수 있다. 이때 함수의 인터페이스에는 타입이 선언된 파라미터 리스트와 리턴 타입을 정의한다. 함수 인테페이스를 구현하는 함수는 인터페이스를 준수하여야 한다.

//함수 인터페이스의 정의
interface SquareFunc {
  (num: number): number;
}

//함수 인터페이스를 구현하는 함수는 인터페이스를 준수하여야 한다.(당욘.ㅎ)
const squareFunc = (num: number): SquareFunc => {
	return num * num;
}

console.log(squareFunc(10)); //100

선택적 프로퍼티

인터페이스의 프로퍼티는 반드시 구현되어야 한다. 하지만 인터페이스의 프로퍼티가 선택적으로 필요한 경우가 있을 수 있다. 선택적 프로퍼티(Optional Property)는 프로퍼티명 뒤에 ?를 붙이며 생략하여도 에러가 발생하지 않는다.

내가 애매할 때 젤 자주 쓰는거 ㅎ...

💫인터페이스 상속💫

인터페이스는 extends 키워드를 사용하여 인터페이스 또는 클래스를 상속받을 수 있다.

interface Person {
  name: string;
  age?: number;
}

interface Student extends Person {
  grade: number;
}

const student: Student =  {
  name: 'Lee',
  age: 20,
  grade: 3
}

복수의 인터페이스를 상속받을 수도 있다.

interface Person {
  name: string;
  age?: number;
}

interface Developer {
  skills: string[];
}

interface WebDeveloper extends Person, Developer {}

const webDeveloper: WebDeveloper =  {
  name: 'Lee',
  age: 20,
  skills: ['HTML', 'CSS', 'JavaScript']
}

나중에 정리하는 것도 나쁘진 않넹
Let it grow!!!

참고!

0개의 댓글