반응형
산술 연산자
- (subtraction) * (multiplication)
/ (division)
% (remainder)
// 산술연산자 에제
let result: number = 1 + 2;
비교 연산자
+ == (equal to)
+ != (not equal to)
+ === (strictly equal to)
+ !== (strictly not equal to)
+ < (less than)
+ > (greater than)
+ <= (less than or equal to)
+ >= (greater than or equal to)
// 비교 연산자 예제
let isOld: boolean = age > 50;
논리 연산자
+ && (logical and)
+ || (logical or)
+ ! (logical not)
// logical example
let isAdult: boolean = age >= 18 && isAdmin; Assignment operators
+ = (assignment)+ += (addition assignment)
+ -= (subtraction assignment)
+ *= (multiplication assignment)
+ /= (division assignment)
+ %= (remainder assignment)
// assignment example
let x: number = 10;
x += 5; // equivalent to x = x + 5;
함수
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3)); // Output: 5
인터페이스
interface Person {
name: string;
age: number;
}
Employee implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
enum
enum Color {
Red,
Green,
Blue,
}
class Car {
color: Color;
constructor(color: Color) {
this.color = color;
}
}
Interfaces와 Enums 연계
interface Vehicle {
color: Color;
wheels: number;
}
enum Color {
Red,
Green,
Blue,
}
class Car implements Vehicle {
color: Color;
wheels: number;
constructor(color: Color, wheels: number) {
this.color = color;
this.wheels = wheels;
}
}
function double<T>(value: T): T {
return value * 2;
}
// Using the double function with numbers
console.log(double(42)); // Output: 84
// Using the double function with strings
console.log(double("hello")); // Output: "hellohello"
Generics는 클래스와 함께 사용할 수 있습니다. 다음은 제네릭을 사용하여 컨테이너 클래스를 만드는 예입니다.
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
const numContainer = new Container<number>(42);
console.log(numContainer.getValue()); // Output: 42
const strContainer = new Container<string>("hello");
console.log(strContainer.getValue()); // Output: "hello"
let myValue: number | string;
myValue = 42;
myValue = "hello";
// Error! MyValue is not a boolean
if (myValue) {
console.log("My value is truthy!");
}
interface Person {
name: string;
}
interface Employee extends Person {
salary: number;
}
let myEmployee: Person & Employee;
myEmployee = { name: "John", salary: 50000 };
// Error! MyEmployee is missing the 'name' property
myEmployee = { salary: 60000 };
interface Person {
name: string;
}
function isPerson(obj: any): obj is Person {
return typeof obj.name === 'string';
}
const person: any = {
name: 'John'
};
if (isPerson(person)) {
console.log(Hello, ${person.name}!);
}
type IsString<T> = T extends string ? true : false;
type StringOrNumber<T> = IsString<T> extends true ? string : number;
const str: StringOrNumber<'hello'> = 'hello';
// type is string const num: StringOrNumber<42> = 42;
// type is number In this
type IsPerson<T> = T extends { name: string } ? true : false;
function isPerson<T>(obj: T): obj is Person {
return IsPerson(obj);
}
const person1: any = { name: 'John' };
if (isPerson(person1)) {
console.log(Hello, ${person1.name}!);
}
TypeError는 연산이 유효하지 않을 때 발생합니다(예: 문자열을 숫자에 더하려고 할 때). ReferenceError는 정의되지 않은 변수나 속성에 접근할 때 발생합니다.
SyntaxError는 코드의 구문에 문제가 있을 때 발생합니다. 이러한 오류 유형을 이해하면 더 견고한 오류 처리 메커니즘을 작성하는 데 도움이 됩니다.
예를 들어, TypeError를 예상하는 경우, 모든 오류를 포착하는 대신 이를 포착하고 구체적으로 처리할 수 있습니다(이 경우 ReferenceError나 SyntaxError와 같은 예상치 못한 유형이 포함될 수 있습니다).
오류 코드
오류 유형 외에도 TypeScript는 오류에 대한 더 많은 컨텍스트를 제공하는 오류 코드를 제공합니다. 이러한 코드는 숫자로 표현되며, 오류 객체의 .code 속성을 사용하여 접근할 수 있습니다.
try {
// Your code here...
} catch (error) {
console.log(Error code: ${error.code});
}
function calculate(x: number, y: number) {
debugger; // Pause here and inspect variables
return x + y;
}
function fetchData(): Promise<string> {
return fetch('https://example.com/data')
.then(response => response.text())
.catch(error => {
console.error(Error fetching data: ${error});
throw error; // Re-throw the error to propagate it up the call stack
});
}
fetchData().then(data => console.log(data));
async function fetchData(): Promise<string> {
try {
const response = await fetch('https://example.com/data'); return await response.text();
} catch (error) {
console.error(Error fetching data: ${error});
throw error; // Re-throw the error to propagate it up the call stack
}
}
fetchData().then(data => console.log(data));
// Good
function calculateTotalPrice(itemPrices: number[]): number {
return itemPrices.reduce((acc, current) => acc + current, 0);
}
// Bad:
function calculateTotalPrice(itemprices: number[]){
return itemprices.reduce(acc=>acc+current,0);
}
// Good:
function calculateTotalPrice(itemPrices: number[]): number {
const subtotal = itemPrices.reduce((acc, current) => acc + current, 0);
return subtotal * (1 + TAX_RATE);
}
// Bad:
function calculateTotalPrice(itemprices: number[]){
return itemprices.reduce(acc=>acc+current,0)*TAX_RATE;
}
// Good:
function isUserAdmin(): boolean {
return userRoles.includes('admin');
}
// Bad:
if (userRoles.includes('admin') && userPermissions.indexOf('edit') !== -1) {
/* ... */
}
function calculateSubtotal(itemPrices: number[]): number {
return itemPrices.reduce((acc, current) => acc + current, 0);
}
import * as React from 'react';
interface Props {
name: string;
}
const Hello: React.FC<Props> = ({ name }) => {
return <div>Hello, {name}!</div>;
};
import { Component } from '@angular/core';
interface Props {
name: string;
}
@Component({
selector: 'app-hello',
template: '<p>Hello, {{ name }}!</p>'
})
export class HelloComponent implements Props {
public name: string;
constructor() {
this.name = 'World';
}
}
const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); });
app.listen(3000, () => {
console.log('Server started on port 3000');
});
import { User } from './user';
const app = express();
app.get('/users', (req, res) => {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
res.json(users);
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
반응형