宮水の日記

宮水の日記

主に書評や資格取得について記事を書いています。

Typescript exercises やってみた 0問目

みなさんこんにちは。宮水です。
今日は、TypeScript エクササイズの0に取り組んでみました。
英語も苦手なので、翻訳も自分でしてみました。

こちらのリポジトリをforkして、cloneして取り組みます。
rootディレクトリで、yarn installしてから問題文にあるRun this exerciseのコマンドを叩くと、答え合わせができます。すごい!!
github.com

本日の問題

import chalk from 'chalk';

/*
Intro:
    We are starting a small community of users. For performance
    reasons we have decided to store all users right in the code.
    This way we can provide our developers with more
    user-interaction opportunities. With user-related data, at least.
    All the GDPR-related issues we will solved some other day.
    This would be the base for our future experiments during
    this workshop.

 私たちは、ユーザーの小さなコミュニティを始めました。
 パフォーマンス上の理由から、全てのユーザー情報をコード上に直接格納することにしました。
 このようにして、少なくともユーザー関連のデータに関して、ユーザーインタラクションの機会を開発者に提供できます。
 全てのGDPR(一般データ保護規則)関連の問題は、別の問題で解決します。このコードは、このワークショップで今後のエクササイズのベースになります。
 
Exercise:
    Given the data, define the interface "User" and use it accordingly.

 「User」インターフェースを定義し、それを使用してください。

Run this exercise:
    npm run 0
    - OR -
    yarn -s 0
*/

const users: unknown[] = [
    {
        name: 'Max Mustermann',
        age: 25,
        occupation: 'Chimney sweep'
    },
    {
        name: 'Kate Müller',
        age: 23,
        occupation: 'Astronaut'
    }
];

function logPerson(user: unknown) {
    console.log(` - ${chalk.green(user.name)}, ${user.age}`);
}

console.log(chalk.yellow('Users:'));
users.forEach(logPerson);

// In case if you are stuck:
// https://www.typescriptlang.org/docs/handbook/interfaces.html#introduction

答え

const users: User[] = [
    {
        name: 'Max Mustermann',
        age: 25,
        occupation: 'Chimney sweep'
    },
    {
        name: 'Kate Müller',
        age: 23,
        occupation: 'Astronaut'
    }
];

interface User {
  name: string;
  age: number;
  occupation: string;
}

function logPerson(user: User) {
    console.log(` - ${chalk.green(user.name)}, ${user.age}`);
}

console.log(chalk.yellow('Users:'));
users.forEach(logPerson);

いえい👏
f:id:kattyan53:20200723224640p:plain


今日は、型定義のやり方と使い方に関する問題でした。
以上です!