Skip to content
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

Typescripts 总结 #96

Open
hsipeng opened this issue Jun 29, 2021 · 0 comments
Open

Typescripts 总结 #96

hsipeng opened this issue Jun 29, 2021 · 0 comments

Comments

@hsipeng
Copy link
Owner

hsipeng commented Jun 29, 2021

总结TypeScript在项目开发中的应用实践体会

条件类型

type B<T> = T extends string ? '1' : '2'

const a: B<string> = '1'
const b:B<number> = '2' // err Type '"1"' is not assignable to type '"2"'

工具类型

  • Readonly
interface Person{
    name: string;
}
type Person2 = Readonly<Person>;

const a: Person2 = {
    name: 'wangly19'
}

const b: Person = {
    name: 'wangly19'
}

a.name = 'wangly19 new'
b.name = 'wangly19 new'
  • Record
    Record<K, V>

  • Pick & Omit

Pick的使用方法是Pick<P, K>,如(P)类型中拥有name,age,desc三个属性,那么K为 name则最终将取到只有name的属性,其他的将会被排出。

interface Person{
    name: string;
	  age: number;
}

type age = Pick<Person, 'age'>

Omit的使用方法是Omit<P, K>,与Pick的结果是相反的,如果说Pick是取出,那么Omit则是过滤的效果

interface Person{
    name: string;
	  age: number;
}

type age = Omit<Person, 'age'>
  • Exclude & Extract
    Exclude使用形式是Exclude<T, S>,如果T中的属性在S不存在那么就会返回
interface A {
    show: boolean,
    hidden: boolean,
    status: string
}

interface B {
    show: boolean,
    name: string
}

type outPut = Exclude<keyof A, keyof B>

Extract:跟Exclude相反,从从一个联合类型中取出属于另一个联合类型的子集

interface A {
    show: boolean,
    hidden: boolean,
    status: string
}

interface B {
    show: boolean,
    name: string
}

type outPut = Extract<keyof A, keyof B>
  • Partial
    Partial是一个将类型转为可选类型的工具,对于不明确的类型来说,需要将所有的属性转化为可选的?.形式,转换成为可选的属性类型。

如何深入学习TypeScript?

当了解TypeScript后,想学习进阶的使用方式,可以看看一些类型库的源码,这些源码内很多TypeScript的操作都能够在其中看到。
比较好的如:utility-types, 里面有一些实用的基本类型,可以对源码进行阅读,阅读难度不大,多动手实践下就会对类型有一个更加清晰的明确。

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

No branches or pull requests

1 participant