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
Author And Source
이 문제에 관하여(TypeScript로 Switch문 작성하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@woojinshim103/TypeScript로-Switch문-작성하기저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)