[英]How to define a simple array of strings in TypeScript
I got a state in React of an Array of strings.我在字符串数组的 React 中得到了 state。
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
?但是如何使用Type
或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'])
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.