Skip to content

学习笔记 #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
coderhyy opened this issue Jun 6, 2022 · 2 comments
Open

学习笔记 #2

coderhyy opened this issue Jun 6, 2022 · 2 comments

Comments

@coderhyy
Copy link
Owner

coderhyy commented Jun 6, 2022

as 的用法

在映射时经常会用到 as 关键词,像下面代码一样

type MappedKey<T> = {
  [K in keyof T as K extends xxx ? never : K]: T[K];
};

这里 as 后面的语句使用来做筛选的

遍历时得到的 K 需要做一些特殊的处理时,比如给 K 加上前缀或后缀,筛选符合某种条件的 K,用 as 连接条件语句

as 是 typescript 4.1 功能,文档链接: Key Remapping in Mapped Type

@coderhyy
Copy link
Owner Author

coderhyy commented Jun 6, 2022

语法糖:交叉类型做约束

利用交叉类型的特性可以做类型约束

type A = "name" & string; // "name"
type B = 1 & string; // never

比如说要对 K 进行约束,是字符串才能使用 Capitalize 方法

使用 extends 关键词进行条件判断,是比较常见的方法,如下:

type A = 1;
type B = { [K in A as K extends string ? Capitalize<K> : never]: K };

交叉类型也是可以用来做约束的,如下:

type C = { [K in A & string as Capitalize<K>]: K };

也可以写成:

type C = { [K in A as Capitalize<K & string>]: K };

@coderhyy
Copy link
Owner Author

coderhyy commented Jun 6, 2022

typeof 的用法

typeof 是用来判断类型的,比如

const a = ["macOS", "Windows", "Linux"];
type b = typeof a; // string[]

const tuple = ["macOS", "Windows", "Linux"] as const;
type c = typeof tuple; // readonly ["macOS", "Windows", "Linux"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant