typescript Pick versus direct property reference

Viewed 26

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.

1 Answers

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
Related