0

I got a state in React of an Array of strings.

I get no errors when doing this:

const [arr, setArr] = useState<Array<string>>([])

const addFilter = (e: React.ChangeEvent<HTMLInputElement>) => {
   const value = e.target.value
   setArr([...arr, value])
}

But how do you define the type with Type or Interface?

1
  • 1
    a List string[] ?, a tuple [string, string]? Commented Mar 1, 2021 at 16:55

1 Answer 1

1

If you want to create an alias for a string array, you can do that using a type:

type StringArray = string[];

const arr: StringArray = [
    'a',
    'b',
    167, // error
    'c'
]

If you want the array + set tuple, it's a similar technique:

type StringArrayAndSet = [string[], Set<string>];

const arrAndSet: StringArrayAndSet = [
    ['a', 'b', 'b', 'c'],
    new Set(['a', 'b', 'b', 'c'])
];
Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see no need for curly brackets, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.