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

【TypeScript】TypeScript之Partial #5

Open
Lydever opened this issue Dec 14, 2021 · 0 comments
Open

【TypeScript】TypeScript之Partial #5

Lydever opened this issue Dec 14, 2021 · 0 comments

Comments

@Lydever
Copy link
Owner

Lydever commented Dec 14, 2021

Partial

Partial 可以快速把某个接口类型中定义的所有属性变成可选的。

举个栗子:

interface ApiKey {
  id: number;
  name: string;
}

const dataType1: ApiKey = {
  id: 1,
  name: 'static'
}

const dataType2: ApiKey = {
  name: 'json'
}

image.png

这段代码会在编译报错:

error TS2741: Property 'id' is missing in type '{ name: string; }' but required in type 'ApiKey'.Key'.

因为dataType2的类型是ApiKey,ApiKey中idname都是必选的,这导致编译报错。假如ApiKey中的参数是可选的,那么这个问题就会不复存在,而Partial的作用就在于此,它可以帮助我们把ApiKey中的所有属性都变成可选的。

我们永Partial来重写一下这个栗子:

interface ApiKey {
  id: number;
  name: string;
}

const dataType1: ApiKey = {
  id: 1,
  name: 'static'
}

const dataType2:  Partial<ApiKey> = {
  name: 'json'
}

这个时候在运行,就不会报错了。

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