Skip to content

Type narrow with typeof or instanceof #619

Answered by dfreeman
swastik asked this question in Q&A
Discussion options

You must be logged in to vote

What you're looking for is a TS feature called type predicates. What you can do is define a method/helper whose return value is a type predicate:

isString(value: unknown): value is string {
  return typeof value === 'string';
}

And then use that in your template:

{{#if (this.isString @foo)}}
  <ComponentThatAcceptsString @foo={{@foo}} />
{{/if}}

Note that due to limitations of the type system itself, it's not possible to express a helper whose return type is a type predicate using helper()/extends Helper—you have to be using a function directly.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by chriskrycho
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants