123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- function startGame() {
- // Starting a new game.
- let playerName: string = 'Audrey';
- logPlayer(playerName);
- const messagesElement: HTMLElement | null = document.getElementById('messages');
- // We know messagesElement cannot be null because we control the markup, so
- // we can use a non-null type assertion
- const element = messagesElement!;
- element.innerText = 'Welcome to MultiMath! Starting a new game';
- console.log('Starting new game');
- }
- function logPlayer(name: string) {
- console.log(`New game starting for player: ${name}.`);
- }
- function arm(doc: HTMLDocument) {
- // We know getElementById() cannot be null because we control the markup, so
- // we can use a non-null type assertion on the function call result.
- doc.getElementById('startGame')!.addEventListener('click', startGame);
- }
- arm(document);
- // Type assertions (not casting, more like in Go).
- let value: any = 42;
- let fixedString1: string = (<number>value).toFixed(2);
- let fixedString2: string = (value as number).toFixed(2);
- console.log(value, fixedString1, fixedString2);
- /**
- * y is now optional, while x is not.
- */
- function foo(x: number, y?: string): string {
- return x.constructor.toString() + y;
- }
- foo(2, "3");
- foo(2);
- function bar(...args: number[]) {
- console.log(args.reduce((accu: number, curr: number) => accu + curr, 0));
- }
- bar(1, 2, 3, 4, 5); // (5+6)/2 = 15
- // Rejected because of noImplicitAny.
- // function qux(x, y) { return x + y; }
- // qux('a', 'b');
- function sendGreeting(greeting: string = "Hello, world"): void {
- console.log(greeting);
- }
- sendGreeting();
- sendGreeting("Hello, moon");
|