TypeScriptを使用したスイッチ文の作成
2836 ワード
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
Reference
この問題について(TypeScriptを使用したスイッチ文の作成), 我々は、より多くの情報をここで見つけました https://velog.io/@woojinshim103/TypeScript로-Switch문-작성하기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol