简体   繁体   中英

How to define a simple array of strings in TypeScript

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM