Notice
Recent Posts
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- 동적객체
- vscode git clone
- maxwidth
- package.json
- 글자들여쓰기
- 정적객체
- npm start
- minwidth
- 아이콘사용법
- npm install 문제
- owlcarousel
- 플러그인
- Git clone
- slickslider
- npm install
- git lab clone
- fontawesome
- MediaQuery
- XEIcon
- node 오류
- 그누보드반응형
- googleicon
- 단어단위로떨어지기
- 웹아이콘
- window 정책변경
- react npm install
- 이미지반응형
- legacy-peer
- node설치
- 의존성문제
Archives
- Today
- Total
어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ
🔵 [React/TypeScript] 타입 추론, 타입 단언 본문
728x90
타입 추론
// 타입 추론
// 마우스 커서를 통해 타입 추론이 어떻게 되었는지 확인
let a = 10;
let b = "hello";
let c = {
id: 1,
name: "홍길동",
profile: {
nickname: "hihihi",
},
urls: ["naver.com"]
}
let { id, name, profile } = c;
let [one, two, three] = [1, "hello", true];
// any타입으로 추론 됨
let d;
d = 10;
// number 타입으로 추론 됨
// any 타입의 진화
d.toFixed();
d = "hello";
// string 타입으로 추론
d.toUpperCase();
// d.toFixed(); // string으로 바꼈기 때문에 number 속성 사용 불가
// const는 리터럴로 추론 => number로 나오지 않고 num: 10 이 표시됨
const num = 10;
const str = "hello";
타입 단언
// 타입 단언
type Person = {
name: string,
age: number
};
// 빈 배열 넣기 (DB에서 값을 뭘 가져올지 모를 때)
let person = {} as Person;
person.name = "홍길동";
person.age = 7;
// person.language = "??"; // 에러
type Dog = {
name: string,
color: string
};
// 타입 단언을 통해 초과 프로퍼티 검사를 피할 수 있음
// DB에서 넘치게 데이터를 줬을 때, Dog에 있는 키값들만 가져와라
let dog: Dog = {
name: "돌돌이",
color: "brown",
breed: "진도"
} as Dog;
// 타입 단언 규칙
// 값 as 단언
// A as B
// A가 B의 슈퍼 타입
// A가 B의 서브 타입
let num1 = 10 as never;
let num2 = 10 as unknown;
// 교집합이 없는 타입은 오류가 발생
// let num3 = 10 as string;
let num3 = 10 as unknown as string;
// const 단언
let num4 = 10 as const;
// const 단언으로 프로퍼티 값을 readonly로 변경
let cat = {
name: "아옹",
color: "yellow"
} as const;
type Post = {
title: string,
author?: string
};
let post: Post = {
title: "게시글1",
author: "홍길동"
};
// number 타입을 지정했을 때 옵셔널 체이닝을 사용하면 에러가 발생
// Not Null 단언 !를 사용해서 null이 아닌 것을 단언해 줄 수 있음
const len: number = post.author!.length;728x90
'개발 > 🔵 React-TypeScript' 카테고리의 다른 글
| react+typescript (0) | 2025.04.05 |
|---|---|
| 🔵 [React/TypeScript] 타입 좁히기, 서로소 유니온 타입 (0) | 2025.04.05 |
| 🔵 [React/TypeScript] 대수타입 (0) | 2025.04.02 |
| 🔵 [React/TypeScript] 타입 호환성 (0) | 2025.04.02 |
| 🔵 [React/TypeScript] 타입 별 예제 2 (0) | 2025.03.30 |
Comments
