0

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?

  • Does this answer your question? [TypeScript array to string literal type](https://stackoverflow.com/questions/44497388/typescript-array-to-string-literal-type) – Simon Hänisch May 11 '20 at 13:08
  • Could you use typescript types instead of array? something like `export type states = 'success' | 'warning' | 'danger';` – Giga Songulashvili May 13 '20 at 14:50

1 Answers1

1

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];

  // ...
}
Simon Hänisch
  • 4,740
  • 2
  • 30
  • 42