TypeScript로 Switch문 작성하기

2518 단어 typescripttypescript

calculater

type Command = 'add' | 'substract' | 'multiply' | 'divide' | 'remainder';
function calculate(command: Command, a: number, b: number): number {
    switch (command) {
        case 'add':
            return a + b;
        case 'substract':
            return a - b;
        case 'multiply':
            return a * b;
        case 'divide':
            return a / b;
        case 'remainder':
            return a % b;
        default:
            throw new Error('unknown command');
    }
}

console.log(calculate('add', 1, 3));
console.log(calculate('substract', 3, 1));
console.log(calculate('multiply', 4, 2));
console.log(calculate('divide', 4, 2));
console.log(calculate('remainder', 5, 2));

result
4
2
8
2
1

game


const position = { x: 0, y: 0 };

function move(direction: 'up' | 'down' | 'left' | 'right') {
    switch (direction) {
        case 'up':
            position.y += 1;
            break;
        case 'down':
            position.y -= 1;
            break;
        case 'left':
            position.x -= 1;
            break;
        case 'right':
            position.x += 1;
            break;
        default:
            throw new Error(`unknown`);
    }
}

console.log(position);
move('up');
console.log(position);
move('down');
console.log(position);
move('left')
console.log(position);
move('right')
console.log(position);

result 
{ x: 0, y: 0 }
{ x: 0, y: 1 }
{ x: 0, y: 0 }
{ x: -1, y: 0 }
{ x: 0, y: 0 }

loading

type LoadingState = {
    state: 'loading';
};

type SuccessState = {
    state: 'success';
    response: {
        body: string;
    };
};

type FailState = {
    state: 'fail';
    reason: string;
}

type ResourceLoadState = LoadingState | SuccessState | FailState;

printLoginState({ state: 'loading' });
printLoginState({ state: 'success', response: { body: 'loaded' } });
printLoginState({ state: 'fail', reason: 'no network' });

function printLoginState(state: ResourceLoadState) {
    switch (state.state) {
        case 'loading':
            console.log('loading...');
            break;
        case 'success':
            console.log(`😃 ${state.response.body}`);
            break;
        case 'fail':
            console.log(`😅 ${state.reason}`);
            break;
        default:
            throw new Error(`unknown state: ${state}`)
    }
}

result
loading...
😃 loaded
😅 no network

좋은 웹페이지 즐겨찾기