포도가게의 개발일지

TypeScript 본문

[JS,TS,Node]

TypeScript

grape.store 2022. 3. 13. 22:39
반응형

filter 메소드 :True값만 passed에 저장시켜줌

 

 

get id: true id retrun / delete id : true만 리턴되기때문에 id가 같은거는 false이므로 delete 됨

 

 

자료형이 변수 뒤에 붙음 변수(: 자료형)

 

 

array 선언 방법 list(변수명) (: 자료형) = 초기화

 

 

c와 달리 어떤 type이 들어오는지 모르는 경우 void 대신 any를 씀 void는 그냥 return값이 없을때 사용

 

 

 

신기한게 다른언어는 선언하면서 타입정해주는데 얘는 변수선언은 var과 let이용 후 type을 뒤에 붙여줌

 

Intersection vs union type

Union type check

interface Bird {
  fly(): void;
  layEggs(): void;
}
 
interface Fish {
  swim(): void;
  layEggs(): void;
}
 
declare function getSmallPet(): Fish | Bird;
 
let pet = getSmallPet();
pet.layEggs();
 
// Only available in one of the two possible types
pet.swim();
Property 'swim' does not exist on type 'Bird | Fish'.
  Property 'swim' does not exist on type 'Bird'.

intersection 과 다르게 그냥 해당 집합으로만 정의되어 잘못된 property또는 method가 포함되어 있지 않다.

Intersection

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}
 
interface ArtworksData {
  artworks: { title: string }[];
}
 
interface ArtistsData {
  artists: { name: string }[];
}
 
// These interfaces are composed to have
// consistent error handling, and their own data.
 
type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;
 
const handleArtistsResponse = (response: ArtistsResponse) => {
  if (response.error) {
    console.error(response.error.message);
    return;
  }
 
  console.log(response.artists);
};

그에 반해 intersection은 합집함으로 정의한다. 때문에 새로 만들어진 집합에 속한 모든 속성에 접근할 수 있게 된다.

 

Utility type

Record<key type, value type>

const test: Record<string, number> = {
  age: 11,
  11: 222
};

console.log(test);

// 출력 { '11': 222, age: 11 }

--------------------------------------------------------------------

interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};
 
cats.boris;

'[JS,TS,Node]' 카테고리의 다른 글

[RxJS] RxJS?  (0) 2022.03.26
[Js] 고급 문법  (0) 2022.03.02
[Node] 작동 원리  (0) 2022.02.09
[Java Script]생성자 함수, Closure, generator  (0) 2022.02.08
[Java Script]호이스팅, 함수 선언문 vs 함수 표현식, this, Promise  (0) 2022.02.04
Comments