强烈推荐:15道TypeScript练习题 [中篇]

写在开头

  • 本次TypeScript一共有15道题,由易道难,可以说是涵盖了所有的使用场景,入门容易,精通难

  • 之前的上集有8道题,没有看过的小伙伴,可以看这之前的文章:

  • 最近技术团队会马上入驻公众号,后期原创文章会不断增多,广告也有,但是大家请理解,这也是创作的动力,大部分收入是会用来发福利,上次就发了一百本书.有的广告还是可以白嫖的课程,点击进去看看也挺好

  • 强烈推荐:15道优秀的TypeScript练习题   (上集)

正式开始

  • 第八题,模拟动态返回数据,我使用的是泛型解题,此时不是最优解法,AdminsApiResponseDatesApiResponse可以进一步封装抽象成一个接口.有兴趣的可以继续优化


interface User {
  type: 'user';
  name: string;
  age: number;
  occupation: string;
}

interface Admin {
  type: 'admin';
  name: string;
  age: number;
  role: string;
}

type responseData = Date;

type Person = User | Admin;

const admins: Admin[] = [
  { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
  { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' },
];

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

type AdminsApiResponse<T> =
  | {
      status: 'success';
      data: T[];
    }
  | {
      status: 'error';
      error: string;
    };


type DatesApiResponse<T> =
  | {
      status: 'success';
      data: T;
    }
  | {
      status: 'error';
      error: string;
    };

function requestAdmins(callback: (response: AdminsApiResponse<Admin>) => void) {
  callback({
    status: 'success',
    data: admins,
  });
}

function requestUsers(callback: (response: AdminsApiResponse<User>) => void) {
  callback({
    status: 'success',
    data: users,
  });
}

function requestCurrentServerTime(
  callback: (response: DatesApiResponse<number>) => void
) {
  callback({
    status: 'success',
    data: Date.now(),
  });
}

function requestCoffeeMachineQueueLength(
  callback: (response: AdminsApiResponse<User>) => void
) {
  callback({
    status: 'error',
    error: 'Numeric value has exceeded Number.MAX_SAFE_INTEGER.',
  });
}

function logPerson(person: Person) {
  console.log(
    ` - ${chalk.green(person.name)}, ${person.age}, ${
      person.type === 'admin' ? person.role : person.occupation
    }`
  );
}

function startTheApp(callback: (error: Error | null) => void) {
  requestAdmins((adminsResponse) => {
    console.log(chalk.yellow('Admins:'));
    if (adminsResponse.status === 'success') {
      adminsResponse.data.forEach(logPerson);
    } else {
      return callback(new Error(adminsResponse.error));
    }

    console.log();

    requestUsers((usersResponse) => {
      console.log(chalk.yellow('Users:'));
      if (usersResponse.status === 'success') {
        usersResponse.data.forEach(logPerson);
      } else {
        return callback(new Error(usersResponse.error));
      }

      console.log();

      requestCurrentServerTime((serverTimeResponse) => {
        console.log(chalk.yellow('Server time:'));
        if (serverTimeResponse.status === 'success') {
          console.log(
            `   ${new Date(serverTimeResponse.data).toLocaleString()}`
          );
        } else {
          return callback(new Error(serverTimeResponse.error));
        }

        console.log();

        requestCoffeeMachineQueueLength((coffeeMachineQueueLengthResponse) => {
          console.log(chalk.yellow('Coffee machine queue length:'));
          if (coffeeMachineQueueLengthResponse.status === 'success') {
            console.log(`   ${coffeeMachineQueueLengthResponse.data}`);
          } else {
            return callback(new Error(coffeeMachineQueueLengthResponse.error));
          }

          callback(null);
        });
      });
    });
  });
}

startTheApp((e: Error | null) => {
  console.log();
  if (e) {
    console.log(
      `Error: "${e.message}", but it's fine, sometimes errors are inevitable.`
    );
  } else {
    console.log('Success!');
  }
});
  • 第九题,还是考察泛型,promisify的编写,传入一个返回promise的函数,函数接受一个参数,这个参数是一个函数,它有对应的根据泛型生成的参数,返回值为void,同样这个函数的参数也为函数,返回值也为void


interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

type Person = User | Admin;

const admins: Admin[] = [
    { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
    { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];

const users: User[] = [
    { type: 'user', name: 'Max
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值