user4540334
user4540334

Reputation:

Stencil web component using imported array as valid prop values

I have a .ts file that exports arrays of valid values for web component properties.

constants.ts

export const states = ['success', 'warning', 'danger'];

I import it in my web component:

example-web-component.tsx

import { Component, Element, Prop, Watch, h } from '@stencil/core';
import { states } from '../../constants';

@Component({
  tag: 'text-input',
  styleUrl: 'text-input.scss',
  scoped: true
})

export class TextInput {
  /**
   * To define state color of Text input
   */
  @Prop({ reflect: true }) state: TYPE_GENERATED_FROM_ARRAY_SHOULD_GO_HERE;


...

@Watch('state')
stateValidation(newValue: string) {
  const validValues = chiStates.join(', ');

  if (newValue && !chiStates.includes(newValue)) {
    throw new Error(`${newValue} is not a valid state for input. If provided, valid values are: ${validValues}. `);
  }
}

  componentWillLoad() {
    this.stateValidation(this.state);
  }

  render() {
    return;
  }
}

My goal is to use this imported array for 2 things:

1) I need it as it is in stateValidation() to throw an error when invalid state is being used;

2) Use this array as TYPE in prop, equivalent to: @Prop({ reflect: true }) state ?: "success" | "warning" | "danger";

What would be the best approach to use the array as TYPE for prop in this case?

Upvotes: 0

Views: 496

Answers (1)

Simon Hänisch
Simon Hänisch

Reputation: 4968

I've flagged this as a duplicate of TypeScript array to string literal type. What you want to do is infer a string literal type from an array. You can do that by using the as const syntax.

export const states = ['success', 'warning', 'danger'] as const;
import { states } from '../../constants';

export class MyComponent {
  @Prop() state: typeof states[number];

  // ...
}

Upvotes: 1

Related Questions