[javascript] Declare an array in TypeScript

I'm having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an undefined error. Am I supposed to use JavaScript syntax or declare a new Array object?

Which one of these is the correct way to create the array?

private columns = boolean[];
private columns = [];
private columns = new Array<boolean>();

How would I initialize all the values to be false?

How would I access the values, can I access them like, columns[i] = true;..?

This question is related to javascript arrays typescript

The answer is


Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);

this is how you can create an array of boolean in TS and initialize it with false:

var array: boolean[] = [false, false, false]

or another approach can be:

var array2: Array<boolean> =[false, false, false] 

you can specify the type after the colon which in this case is boolean array


Specific type of array in typescript

export class RegisterFormComponent 
{
     genders = new Array<GenderType>();   // Use any array supports different kind objects

     loadGenders()
     {
        this.genders.push({name: "Male",isoCode: 1});
        this.genders.push({name: "FeMale",isoCode: 2});
     }
}

type GenderType = { name: string, isoCode: number };    // Specified format

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];

let arr1: boolean[] = [];

console.log(arr1[1]);

arr1.push(true);

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with arrays tag:

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? How to update an "array of objects" with Firestore? How to increment a letter N times per iteration and store in an array? Cloning an array in Javascript/Typescript use Lodash to sort array of object by value TypeScript enum to object array How do I check whether an array contains a string in TypeScript? How to use forEach in vueJs? Program to find largest and second largest number in array How to plot an array in python? How to add and remove item from array in components in Vue 2 console.log(result) returns [object Object]. How do I get result.name? How to map an array of objects in React How to define Typescript Map of key value pair. where key is a number and value is an array of objects Removing object from array in Swift 3 How to group an array of objects by key Find object by its property in array of objects with AngularJS way Getting an object array from an Angular service push object into array How to get first and last element in an array in java? Add key value pair to all objects in array How to convert array into comma separated string in javascript Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Angular 2 declaring an array of objects How can I loop through enum values for display in radio buttons? How to convert JSON object to an Typescript array? Angular get object from array by Id Add property to an array of objects Declare an array in TypeScript ValueError: all the input arrays must have same number of dimensions How to convert an Object {} to an Array [] of key-value pairs in JavaScript Check if a value is in an array or not with Excel VBA TypeScript add Object to array with push Filter array to have unique values remove first element from array and return the array minus the first element merge two object arrays with Angular 2 and TypeScript? Creating an Array from a Range in VBA "error: assignment to expression with array type error" when I assign a struct field (C) How do I filter an array with TypeScript in Angular 2? How to generate range of numbers from 0 to n in ES2015 only? TypeError: Invalid dimensions for image data when plotting array with imshow()

Questions with typescript tag:

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type? ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead What is "not assignable to parameter of type never" error in typescript? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How to convert string to boolean in typescript Angular 4 What is the Record type in typescript? Angular: How to download a file from HttpClient? Angular 6: saving data to local storage Sort Array of object by object field in Angular 6 How to use `@ts-ignore` for a block Setting values of input fields with Angular 6 Select default option value from typescript angular 6 Angular 6: How to set response type as text while making http call How to do a timer in Angular 5 Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Angular 5 Button Submit On Enter Key Press Importing json file in TypeScript Angular - "has no exported member 'Observable'" Property '...' has no initializer and is not definitely assigned in the constructor How to remove whitespace from a string in typescript? Angular 5 - Copy to clipboard Angular 5, HTML, boolean on checkbox is checked js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check document.getElementById replacement in angular4 / typescript? Exclude property from type How to iterate using ngFor loop Map containing key as string and values as map iteration Read response headers from API response - Angular 5 + TypeScript 'mat-form-field' is not a known element - Angular 5 & Material2 Angular 5 Scroll to top on every Route click Angular File Upload Property 'value' does not exist on type 'Readonly<{}>' No provider for Http StaticInjectorError How to get query parameters from URL in Angular 5? Angular Material: mat-select not selecting default Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf No provider for HttpClient I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular Add items in array angular 4 Angular 4 checkbox change value How to import JSON File into a TypeScript file? How to generate components in a specific folder with Angular CLI?