728x90
반응형
타입을 미리 정하기 애매할 때
- typescript에서는 any타입보다 unknown 타입을 권장
- 연산은 오직 number, bitint 등 타입에서만 가능하고 unknown, any타입, string | number 등 에서는 불가능
let name: string = "name";
let age: number = 50;
let married: boolean = true;
let members: string[] = ["kim", "park"];
let member: (string | number)[] = [123, "123"]; // 소괄호 필수
let anyName: any = true;
let unknownName: unknown; // 권장
unknownName = 123;
unknownName = true;
let test: string = anyName; // any를 쓰면 타입에러 잡지 못하고
// test = unknownName; // unknown을 쓸 경우 마지막 초기화된 타입을 기준으로 타입에러 잡아준다. (권장))
// unknownName - 1; // 연산 사용 불가능
type newType = {
[key: string]: string;
};
let newAge: string | number;
// newAge + 1;
let test2 = "kim" + 1;
// string +1 (허용)
// number +1 (허용)
// string | number +1 (NO!)
// unknown 도 마찬가지!
let user :undefined = undefined
let chulsu : (string | undefined | boolean)[] = [user]
type schoolType = {
score : (number | boolean)[],
teacher :string,
friend : string | string[]
}
// < 연습문제 > 선언 아래 값 주입시 에러코드가 없도록 타입 지정해주기
// 해당 타입은 위의 schoolType이 답이다.
let school : schoolType = {
score : [100, 97, 84],
teacher : 'phill',
friend : 'john'
}
school.score[4] = false
school.friend = ['Lee', school.teacher]
함수에 타입지정하는 법 & void 타입
import { stringify } from "querystring";
import React from "react";
// 타입지정된 파라미터는 필수(자바스크립트와 차이점)
function func(x: number): number {
return x * 2;
}
func(30);
// 파라미터 변수 뒤에 ?(물음표) 써주면 파마리터를 옵션으로 만들 수 있다.
// x?의 의미는 == x : number | undefinded
function voidFunc(x?: number): void {
// return 1 + 1 // ERROR
}
// <연습문제>
function prac1(x?: unknown): void {
if (x == null) {
console.log("no name");
} else {
console.log(x);
}
}
function accountLength(x: string | number): number {
return x.toString.length;
}
type userType = {
monthlyImcome: number;
hasHouse: boolean;
charming: string;
};
function probability(x: userType) :string {
let totalScore = 0;
let result :string;
totalScore += x.monthlyImcome;
if (x.hasHouse) totalScore += 500
if (x.charming === '상') totalScore += 100
if (totalScore>=600) {
result = '결혼 가능'
} else {
result = '결혼 불가능'
}
return result;
}
prac1();
prac1(5);
타입 확정하기 : Narrowing & Assertion
unction funcNarrowing(x: number | string) {
if (typeof x === "string") {
return x + 1;
} else {
return x + 1;
}
}
function funcNarrowing2(x: number | string) {
let array: number[] = [];
if (typeof x === "number") {
array[0] = x;
} else {
// 간혹 else가 없으면 에러 발생
}
}
// narrowing을 판별해주는 문법들
// type of 변수
// 속성명 in 오브젝트 자료
// 인스턴스 instanceof 부모
// 또는 assertion 문법, 타입덮어쓰기
// 편해보이지만 용도를 잘 알고 사용해야한다.
// 용도 1. narrowing 할때 쓴다
// 예외 : 이미 선언된 변수의 타입을 변경할 때 사용하지 않는다.
// 용도 2. 무슨 타입이 들어올지 100% 확실할 때 사용한다.
// 따라서 대부분 if문 사용한다! (디버깅용, 비상용)
function funcNarrowwing(x: number | string) {
let array: number[] = [];
array[0] = x as number;
}
728x90
반응형
'Web > Typescript' 카테고리의 다른 글
[Typescript]함수와 메소드에 type alias 지정 (0) | 2022.06.12 |
---|---|
[Typescript]Literal Type로 만드는 const 변수 유사품 (0) | 2022.06.11 |
[Typescript]타입변수에 담기(type alias) & 타입 extend하기 (0) | 2022.06.11 |
[Typescript]컴파일시 세부설정(tsconfig.json) (0) | 2022.06.11 |
[Typescript]설치셋팅&기본문법 (0) | 2022.06.11 |