TypeScript
Everyday Types
wqdsdsf
2023. 12. 20. 16:21
<Typescript에서 string,number 인것처럼 소문자로 해주어야한다
number,string, boolean, symbol = primitive type
Number, String, Boolean, Symbol = Reference Type>
string : string 타입은 텍스트 데이터를 나타냅니다.
작은 따옴표(’), 큰 따옴표(”), 백쿼트(`) 를 사용하여 문자열을 표현할 수 있습니다.
ex) let myName: string = "Alice";
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
number : number 타입은 TypeScript에서 사용하는 모든 숫자(short, int, long, float, double)를 나타냅니다
ex) function calculateArea(radius: number): number {
return Math.PI * radius * radius;
}
boolean : boolean 타입은 참(true) 또는 거짓(false) 값을 나타냅니다.
ex) function isValidPassword(password: string): boolean {
return password.length >= 8;
}
any : TypeScript에서 any 타입은 모든 타입의 슈퍼 타입(어떠한 값이든 저장 가능 하지만 이걸 사용한다면 Typescript를 사용하는 이유가 없다)
ex) let obj: any = { x: 0 };
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;
Object Types : Object type을 정의하려면 해당 속성과 유형을 나열하기만 하면 됩니다.
ex) function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });
Optional Properties : 해당 속성의 일부 또는 전부를 선택 사항으로 지정할 수도 있습니다(?)
ex) function printName(obj: { first: string; last?: string }) {
// ...
}
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
Union Types : 여러 타입 중 하나를 가질 수 있는 변수를 선언할 때 사용
ex) type StringOrNumber = string | number;
Type Aliases || Interfaces:
ex) type Point = {
x: number;
y: number;
};
// Exactly the same as the earlier example
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 });
interface 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 });