How can I make an empty string array in Typescript?
The definition of string array should be:
// instead of this
// var errors: [string];
// we need this
var errors: string[];
errors = [];
Note: another issue could be the parameter key here
...forEach(function (key) {...
I would guess that we often should declare two of them, because first is very often value, second key/index
Object.keys(response.data.modelState)
.forEach(function (value, key) {
errors.push.apply(errors, response.data.modelState[key]);
});
And even, we should use arrow function, to get the parent as this
Object.keys(response.data.modelState)
.forEach( (value, key) => {
errors.push.apply(errors, response.data.modelState[key]);
});
TypeScript: Creating an empty typed container array
The existing answers missed an option, so here's a complete list:
// 1. Explicitly declare the type
var arr: Criminal[] = [];
// 2. Via type assertion
var arr = <Criminal[]>[];
var arr = [] as Criminal[];
// 3. Using the Array constructor
var arr = new Array<Criminal>();
Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.
The advantage of using a type assertion (sometimes called a cast, but it's not really a cast in TypeScript) works for any expression, so it can be used even when no variable is declared. There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.
Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable. However, there is a slight performance impact at runtime*. Also, if someone were crazy enough to redefine the Array constructor, the meaning could change.
It's a matter of personal preference, but I find the third option the most readable. In the vast majority of cases the mentioned downsides would be negligible and readability is the most important factor.
*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.
Creating array of empty strings?
Update: on newer browsers - use .fill
: Array(1000).fill('')
will create an array of 1000 empty strings.
Yes, there is a way:
var n = 1000;
Array(n).join(".").split("."); // now contains n empty strings.
I'd probably use the loop though, it conveys intent clearer.
function repeat(num,whatTo){
var arr = [];
for(var i=0;i<num;i++){
arr.push(whatTo);
}
return arr;
}
That way, it's perfectly clear what's being done and you can reuse it.
How to tell typescript to accept an empty array or a function
This is a common misconception. [() => void]
is a tuple of one element, and that element needs to satisfy the type () => void
. If you want an array, let it be empty or not, with one or multiple elements, the correct type is (() => void)[]
.
The following expressions are accepted by (() => void)[]
:
[]
[() => { doSomething(); }]
[() => { doSomething(); }, () => { doSomethingElse(); }]
While only the expression number 2 is accepted by [() => void]
.
If you want either an empty array or a tuple of one element, you can just do [] | [() => void]
Related Topics
Detect If Html5 Video Element Is Playing
Getting an Array of Column Names At Sheetjs
How to Match Only the Exact Word Using Indexof or Includes in JavaScript
Detecting When User Scrolls to Bottom of Div With React Js
How to Refresh the Data in a Jqgrid
How to Remove HTML Element from Dom With React
Es6/Babel Class Constructor Cannot Be Invoked Without 'New'
Datatables - Search in Multiple Columns With a Single Drop Down
React Js - How to Get Click Event Values from Child Component to Parent Component
Cannot Open Local File - Chrome: Not Allowed to Load Local Resource
How to Convert Uint8 Array to Base64 Encoded String
How to Create a Dynamic Jquery Data Table With Json Data and Ajax
Uncaught Typeerror: (Intermediate Value)(...) Is Not a Function
Export Array of Objects into Excel Using JavaScript
Handle File Download from Ajax Post
Trigger JavaScript Event If Div Innertext Change
Javascript: Refresh Same Page With Query String from Selects
Javascript and Getelementbyid for Multiple Elements With the Same Id