TypeScript类型级别实例代码分析

发布时间:2023-02-27 11:51:42 作者:iii
来源:亿速云 阅读:171

本篇内容介绍了“TypeScript类型级别实例代码分析”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

代码如下:

/**
 * Try assigning "World" to `type Hello`!
 */
type Hello = "...";
// Type-level unit tests!
// If the next line type-checks, you solved this challenge!
type test1 = Expect<Equal<Hello, "World">>;

多年来,TypeScript的类型系统已经从基本的类型注释发展成为一种大型复杂的编程语言。如果你曾经研究过一个开源库的代码,你可能会发现一些看起来很吓人、很陌生的类型,比如来自另一个星球的一些深奥的语言。库代码通常需要比我们习惯编写的代码更抽象;

这就是为什么它广泛使用高级TypeScript功能,如泛型、条件类型、映射类型甚至递归类型。我个人在研究TS Pattern时学习了这些概念,这是一个开源库,具有极其难以键入的特殊性。在本课程中,我希望分享我通过阅读过多的源代码和对类型系统进行数百小时的修改所学到的知识。

类型之所以很棒,有很多原因:

类型系统对您的代码了解得越多,它对你的帮助就越大!一旦你精通TypeScript,一切都变得可能。您将不再觉得类型系统限制了您编写所需抽象的能力。

想不想检查路由参数传递的是否正确?

走你:

// ✅ this is correct ????
navigate("user/:userId", { userId: "2" });
// ✅ Looks good! `dashboardId` is optional.
navigate("user/:userId/dashboard(/:dashboardId)", { userId: "2" });
// ❌ `userId` is missing. Add one to fix the error!
navigate("user/:userId/dashboard(/:dashboardId)", { dashboardId: "2" });
// ❌ `oops` isn't a parameter. Remove it to fix the error!
navigate("user/:userId/dashboard(/:dashboardId)", { userId: "2", oops: ":(" });
// ???? Scroll to see how this works!
// ???? Here are the kind of things you will soon be able to do!
type ParseUrlParams<Url> =
  Url extends `${infer Path}(${infer OptionalPath})`
    ? ParseUrlParams<Path> & Partial<ParseUrlParams<OptionalPath>>
    : Url extends `${infer Start}/${infer Rest}`
    ? ParseUrlParams<Start> & ParseUrlParams<Rest>
    : Url extends `:${infer Param}`
    ? { [K in Param]: string }
    : {};
// navigate to a different route
function navigate<T extends string>(
  path: T,
  params: ParseUrlParams<T>
) {
  // interpolate params
  let url = Object.entries<string>(params).reduce<string>(
    (path, [key, value]) => path.replace(`:${key}`, value),
    path
  );
  // clean url
  url = url.replace(/(\(|\)|\/?:[^\/]+)/g, '')
  // update url
  history.pushState({}, '', url);
}

“TypeScript类型级别实例代码分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 在typescript项目中安装web3一直提示错误node-gyp rebuild怎么办
  2. 写TypeScript代码的1坏习惯有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

typescript

上一篇:node如何连接redis

下一篇:在VScode里如何添加Python解释器

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》