Interface

Leutbing·2023년 6월 24일
0
post-thumbnail

Interface

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

  • ES6는 인터페이스를 지원하지 않는다.
  • TypeScript는 인터페이스를 지원한다.

인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점에서 클래스와 유사하나 직접 인스턴스를 생성할 수 없고 모든 메소드는 추상 메소드이다. 단, 추상클래스의 추상 메소드와 달리 abstract 키워드를 사용하지 않는다.

변수 & Interface

인터페이스는 변수의 타입으로 사용할 수 있다.

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

//변수 user의 타입으로 User 인터페이스를 선언하였다.
let user : User;

//변수 user는 User 인터페이스를 준수하여야 한다.
user = {id : 1, number : 1000, content : 'frontEnd', completed : false}

함수 & Interface

인터페이스를 사용하여 함수 파라미터의 타입을 선언할 수 있다.
해당 함수에는 함수 파라미터의 타입으로 지정한 인터페이스를 준수하는 인수를 전달하여야 한다.
함수에 객체를 전달할 때 복잡한 매개변수 체크가 필요없어서 매우 유용하다.

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

let users : User[] = [];

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

const newUser : User = {id : 1, number : 1000, content : 'frontEnd', completed : false}

addTodo(newUser);
console.log(users)

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

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

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

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

선택적 프로퍼티

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

interface UserInfo{
	username : string;
	password : string;
  	age ?: number;
  	address ?: string;
}

const userInfo : UserInfo = {
	username : 'spdhsrnvl123@naver.com',
  	password : '123456'
}

console.log(userInfo);

인터페이스 상속

인터페이스는 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 webDevloper : WebDeveloper = {
	name : "Lee",
  	age : 20,
  	skills : ['HTML', 'CSS', 'JavaScript']
}

Interface & styled-components

styled-component에 typescript적용 <인터페이스명>를 붙여주면 된다.

Circle.tsx


interface ContainerProps{ 
	bgColor : string
}
//styled-component에 typescript적용
const Container = styled.div<ContainerProps>` 
	width:200px;
	height:200px;
	background-color: ${props => props.bgColor};
`

interface CircleProps{
	bgColor : string;
}

function Circle({bgColor}:CircleProps){
	return <Container bgColor={bgColor} />;
}

export default Circle;

App.tsx

import Circle from "./Circle";

function App(){
	return(
		<div>
      		<Circle /> //CircleProps에서 지정한 타입의 props가 없기 때문에 에러 발생
      		<Circle bgColor = "tomato" />
		</div>
    )
}

0개의 댓글