TypeScript 练习题

点击蓝色“脑洞前端”关注我哟

加个“星标”,带你揭开大前端的神秘面纱!

这是脑洞前端第「105」篇原创文章

TypeScript 的学习资料非常多,其中也不乏很多优秀的文章和教程。但是目前为止没有一个我特别满意的。原因有:

  • 它们大多数没有一个清晰的主线,而是按照 API 组织章节的,内容在「逻辑上」比较零散。

  • 大多是“讲是什么,怎么用“,而不是”讲为什么,讲原理“。

  • 大多数内容比较枯燥,趣味性比较低。都是干巴巴的文字,没有图片,缺乏能够引起强烈共鸣的例子。

因此我的想法是做一套不同市面上大多数的 TypeScript 学习教程。以人类认知的角度思考问题,学习 TypeScript,通过通俗易懂的例子和图片来帮助大家建立 TypeScript 世界观。

系列安排:

目录将来可能会有所调整。

注意,我的系列文章基本不会讲 API,因此需要你有一定的 TypeScript 使用基础,推荐两个学习资料。

  • 深入理解 TypeScript[1]

  • TypeScript 官方文档[2]

结合这两个资料和我的系列教程,掌握 TypeScript 指日可待。

接下来,我们通过几个方面来从宏观的角度来看一下 TypeScript。

前言

本文涉及的题目一共十六道,全部都可以在 typescript-exercises[3] 上在线提交。

可以和标准答案进行对比。

并且由于使用了浏览器缓存, 因此无需登录的情况下也可以保证关掉页面,你的答题进度也会保留。

想重置进度,清空缓存,无痕模式或者换浏览器都可以。

题目中涉及到的知识点我基本也都在之前的文章中提到了,如果你没有看过,强烈建议先完成前面的教程,然后将上面的题目自己做一遍之后再看本文。

为了不让文章太过于冗长, 本篇文章分两次发布, 一次 8 道题,一共十六道。每道题都有思路,前置知识以及代码。

题目一

题目描述

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
    these exercises.

Exercise:

    Given the data, define the interface "User" and use it accordingly.

题目的大概意思是让你定义一个类型 User, 使得代码可以正常运行。

题目内置代码

export type User = unknown;

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

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

console.log("Users:");
users.forEach(logPerson);

前置知识

  • interface 或 type 声明自定义类型

思路

这道题比较简单, 我们只有定义一个 User 类即可。从 users 数组中不难看出, User 中有三个属性 name ,age 和 occupation,类型分别为 string, number 和 string。因此直接使用 type 或者 interface 定义自定义类型即可。

代码

核心代码:

export type User = {
  name: string;
  age: number;
  occupation: string;
};

题目二

题目描述

Intro:

    All 2 users liked the idea of the community. We should go
    forward and introduce some order. We are in Germany after all.
    Let's add a couple of admins.

    Initially we only had users in the in-memory database. After
    introducing Admins, we ne
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值