Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- npm styled-reset
- git lab
- API 토큰
- styled components
- dart 변수
- 컨디셔널 렌더링
- API token
- ngrok실행
- icon
- fetch
- bootstrap
- nextjs .env
- github
- next.js css
- Git
- nextjs 설치
- nextjs
- input type=file
- github io
- react
- There isn’t anything to compare
- typescript react
- CSS
- SCSS
- react env
- react typescript
- getModifierState
- ngrok설치
- createGlobalStyle
- rewrites
Archives
- Today
- Total
꾸준히 성장하는 개발자
[TypeScript] interface / Type Aliases(타입 별칭) 본문
interface
-인터페이스는 상호 간에 정의한 약속 혹은 규칙을 의미한다
- 타입스크립트에서의 인터페이스는 보통 다음과 같은 범주에 대해 약속을 정의할 수 있다.
- 객체의 스펙(속성과 속성의 타입)
- 함수의 파라미터
- 함수의 스펙(파라미터, 반환 타입 등)
- 배열과 객체를 접근하는 방식
- 클래스
interface User{
age:number;
name:string;
}
변수에 인터페이스 활용
var seho :User={
age:33,
name:'세호'
}
함수에 인터페이스 활용
function getUser(user:User){
console.log(user)
}
const capt={
name:"캡틴",
age:100
}
getUser(capt);
함수의 스펙(구조)에 인터페이스를 활용
interface SumFunction{
(a:number, b:number):number;
}
var sum:SumFunction;
sum=function(a:number,b:number):number{
return a+b;
}
인덱싱
interface StringArray{
[index:number]:string;
}
var arr2:StringArray=['a','b','c'];
arr2[0]=10; // 에러 발생
딕셔너리 패턴
interface StringRegexDicrionary{
[key:string]:RegExp;
}
var obj2:StringRegexDicrionary={
//sth:/abc/,
cssFile:/\.css$/,
jsFile:/\.js$/
}
obj2['cssFile']='a' // 에러발생
인터페이스 확장
interface Person{
name:string;
age:number;
}
// interface Developer{
// name:string;
// age:number;
// language:string;
// }
// -> 확장 : extends 후 더해줄 interface를 입력하면 함께 포함이 되어
// 위의 주석된 developer와 같이 표현이 된다.
interface Developer extends Person{
language:string;
}
var captain:Developer={
language:'ts',
age:100,
name:'캡틴'
}
Type Aliases (타입 별칭)
특정타입이나 인터페이스를 참조할 수 있는 타입 변수를 의미한다.
타입별칭은 새로운 타입 값을 하나 생성하는 것이 아니라
정의한 타입에 대해 나중에 쉽게 참고할 수 있게 이름을 부여하는것과 같다
type Person={
name:string;
age:number;
}
var seho:Person={
name:'세호',
age:30
}
type MyString = string;
var str : MyString ='hello';
type vs interface
타입별칭과 인터페이스의 가장 큰 차이점은 타입의 확장가능/ 불가능이다
인터페이스는 확장이 가능하지만 타입 별칭은 확장이 불가능하다
좋은 소프트웨어는 언제나 확장이 용이해아 한다는 원칙에 따라
가급적 확장이 가능한 인터페이스로 사용하는 것을 권장한다.
'Typescript' 카테고리의 다른 글
[eslint에러] Delete `␍`eslint prettier/prettier (0) | 2022.10.18 |
---|---|
[TypeScript] eslint 노란 밑줄이 나타나지 않을 때 (0) | 2022.09.15 |
[TS] 라이브러리 설치와 tsc (0) | 2022.09.11 |
TypeScript Basic Types (0) | 2022.01.05 |
TypeScript 란 ? (0) | 2021.12.24 |