简体   繁体   中英

typescript Pick versus direct property reference

I know there's Pick feature in typescript, like so

type Article = {
  title: string;
  body: string;
  image: string;
}

type ArticlePreview = Pick<Article, 'title'>

but actually you can access the property

type ArticleTitle = Article['title']

what's the advantage of using Pick? I see the second option is more simple and straight forward.

It computes a different type, the two types have different usage ( ArticlePreview vs ArticleTitle ).

  • ArticlePreview: we compute a type subset of the Article type;
  • ArticleTitle: we retrieve the type of the title property from the Article type.
type ArticlePreview = Pick<Article, 'title'>;
// equivalent to:
type ArticlePreview = { title: string };
// or to:
type ArticlePreview = { title: Article['title'] };
// You could pick more properties using union inside the generic
type ArticlePreview2 = Pick<Article, 'title' | 'image'>

// While

type ArticleTitle = Article['title']
// is equivalent to:
type ArticleTitle = string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM