사내스터디 1일차 정리내용
회고
string
: "Hello, world"
number
: 42
int
나 float
, double
등 세부적으로 숫자형태가 구분되지 않음.number
boolean
: true
/ false
//Type annotation - : 를 이용하여 js 코드에 타입을 정의하는 방식
//string
let str: string = 'hi';
//number
let num: number = 10;
//boolean
let isLoggedIn: boolean = false;
[1, 2, 3]
or Array<number>
형태로 선언, string[]
/ number[]
의 형태로도 선언가능.[number]
의 형태로 사용하면 숫자의 집합이라는 뜻으로 Array
가 아닌 Tuple
에 해당함.let arr: number[] = [1,2,3];
let arr: Array<number> = [1,2,3];
let arr: [string, number] = ['hi', 10];
enum Avengers { Capt, IronMan, Thor}
let hero: Avengers = Avengers.Capt;
console.log(hero); //Capt에 해당하는 인덱스번호 0이 출력됨
let hero2: Avengers = Avengers[0];
console.log(hero2); //"Capt"
any
타입이 붙으면 타입검사를 통과하게 되서 안정성을 낮추는 타입이기도함.undefined
와 null
만 할당하고 함수에는 반환값을 설정할 수 없는 타입//BigInt function으로 생성하거나
const oneHundred: bigint = BigInt(100);
//literal syntax로 bigint를 생성
const anotherHundred: bigint = 100n;
number
, string
과 같은 기본자료형 ( ES2015부터 )//Symbol 생성자를 호출해서 생성
let sym1 = Symbol();
//생성된 symbol은 불변하고 유일하기 때문에 아래 두개값은 비교했을 때 false
let sym2 = Symbol("key");
let sym3 = Symbol("key");
sym2 === sym3;
//심벌은 객체 프로퍼티의 키로 사용할 수도 있음
const sym = Symbol();
let obj = {
[sym]: "value"
};
console.log(obj[sym]); //"value"
,
또는 ;
를 사용any
타입으로 간주됨.?
를 붙이면 옵셔널 property가 되서 필수로 필요하지 않은 값이 됨.undefined
로 로그 출력됨undefined
일 수도 있으므로 undefined
여부를 먼저 확인해야됨.function printName(obj: { first: string; last?: string }) {
// ...
console.log(obj.first);
console.log(obj.last);
}
// 둘 다 OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
![[Pasted image 20221017132238.png]]
Array.isArray(파라미터)
함수로 좁혀서 사용가능slice
메서드를 내장하고 있음.function printId(id: number | string) {
console.log("ID : " + id);
//오류 : string 타입에만 유효한 메서드는 사용할 수 없음. 반대로 number 타입에만 유효한 메서드도 사용할 수 없음.
console.log(id.toUpperCase());
// typeof로 타입범위를 좁혀서 사용 가능
if (typeof id === "string") {
//여기는 string 타입
} else {
//여기는 number 타입
}
}
// OK
printID(101);
// OK
printID("202");
// 오류 : number나 string에 해당하지 않기 때문에 오류
printId({ myID : 22342});
function welcomePeople(x: string[] | string) {
if (Array.isArray(x)) {
// 여기에서 'x'는 'string[]' 타입입니다
console.log("Hello, " + x.join(" and "));
} else {
// 여기에서 'x'는 'string' 타입입니다
console.log("Welcome lone traveler " + x);
}
}
string
타입으로 리턴되고 number
, string
, boolean
, symbol
, bigint
, undefined
, object
, function
형태로 리턴됨 ( 주로 원시타입들 )type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
// n in x = "swim" in animal
// 여기서 n : swim 은 문자열 리터럴 타입이고
// x : animal 은 유니언 타입
if ("swim" in animal) {
//swim 프로퍼티가 있는 Fish Type에 해당
return animal.swim();
}
//swim 프로퍼티가 없는 Bird Type에 해당
return animal.fly();
}
function logValue(x: Date | string) {
if (x instanceof Date) {
//logValue(new Date()); 로 함수 호출한 경우에는 이쪽으로 분기됨.
console.log(x.toUTCString());
} else {
//new Date가 아닌 그 외 string의 경우 이쪽으로 분기
console.log(x.toUpperCase());
}
}
interface
타입도 별칭 부여 가능 type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
// 유니언 타입에 별칭을 부여한 경우
type ID = number | string;
object
타입을 만드는 또 다른 방법interface personAge {
age: number;
}
function logAge(obj: personAge) {
console.log(obj.age);
}
//여기서 name 하나 더 들어갔다고 해서 오류 안나고
//age를 먼저 넣는다고 해서 오류 안남.
let person = { name: 'Capt', age: 28 };
logAge(person);
//속성앞에 readonly 추가
interface Car {
readonly brand: string;
}
let myCar: Car = {
brand: 'Audi'
};
//readonly 속성이기 때문에 에러발생
//Cannot assign to 'brand' because it is a read-only property.
myCar.brand = "genesis";
interface login {
//함수인자 1,2의 타입정의 : 반환값의 타입을 정의
(username: string, password: string): boolean;
}
//login 인터페이스를 이용하여 타입을 먼저 정의하고
//그 다음 함수의 동작을 정릐
let loginUser: login;
loginUser = function(id: string, pw: string) {
console.log('로그인 했습니다.');
return true;
}
//extends로 인터페이스간 확장 가능
interface Person {
name: string;
}
interface Developer extends Person {
skill: string;
}
interface
가 가지는 대부분의 기능은 type
에서도 동일하게 사용가능interface
) / 불가능(type
)SOLID
원칙 중 O
에 따라서 확장이 가능한 interface
로 선언하면 더 좋음.let shouldString: any = 'hi';
//shouldString 이 string 타입인걸 확실히 알고 있는 경우
//typescript를 JSX와 사용할 때는 이 스타일로는 사용할 수 없음.
let stringLength: number = (<string>shouldString).length;
//or
//type assertions - as 문법으로 지정
let stringLength: number = (shouldString as string).length;
as
스타일로 써야함.