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

Type narrowing not working with current setup #130

Open
programm-ingovals opened this issue Nov 28, 2022 · 1 comment
Open

Type narrowing not working with current setup #130

programm-ingovals opened this issue Nov 28, 2022 · 1 comment

Comments

@programm-ingovals
Copy link

Using the generated types I assume that type narrowing would work fine.

const embeddedEntry = (entry: IEntry) => {
  switch (entry.sys.contentType.sys.id) {
    case 'article':
      entry.fields // Should be known as IArticleFields here
      break
    case 'page':
      entry.fields  // Should be known as IPageFields here
}

Weirdly this does not seem to work, even though IArticleEntry should be the only one to have sys.contentType.sys.id as "article".
Is it because of the generic typing?

@bogdansoare
Copy link

bogdansoare commented Feb 19, 2023

I faced the same issue and I think it's a limitation from typescript, I ended up using Type predicates to narrow down the type.

As an example you could try:

function isArticle(entry: IEntry): entry is IArticleFields {
  return entry.sys.contentType.sys.id === 'article'
}

The downside is that it doesn't work very well with switch statements.

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

2 participants