Typescript cast to array

How to cast to array in TypeScript 2?

I had some code that cast an object to type array (so I could use array functions on the object without compile errors).

 var n = (result.data['value'] as []).map( (a)=>< //.. >); 

But on upgrade to ts2, I get:

error TS1122: A tuple type element list cannot be empty.

Which is actually a syntax error, claiming you forgot a comma or value. So, how do I modify this cast to work correctly?

I tried as [IMyType] and it worked, but I’d prefer not to specify type since I only need the array.prototype functions here. also, I don’t think that’s how you actually do it.

FlavorScape

People also ask

There are 4 possible conversion methods in TypeScript for arrays: let x = []; //any[] let y1 = x as number[]; let z1 = x as Array; let y2 = x; let z2 = x; The as operator’s mostly designed for *. tsx files to avoid the syntax ambiguity.

Converting a variable from one type to another is possible with type casting in Typescript. Type casting in TypeScript can be done with the ‘as’ keyword or the ‘<>‘ operator.

3 Answers

For some reason the compiler thinks that result.data[‘value’] is a tuple and not an array.

You can cast it like this:

Which should tell the compiler that it’s an array, or:

If your array has only items of type IMyType then simply:

result.data['value'] as IMyType[] 

However, if your array contains items of different types then it’s either a any[] or a tuple, for example:

result.data['value'] as [IMyType, string, string] 

In any case, in the compiled js it will be an array, but tuples let you define a fixed length arrays with specific types.

Nitzan Tomer Avatar

answered Nov 06 ’22 06:11

Nitzan Tomer

You’re not casting to an array.

[string] is a tuple with a single element string . [string, string] is a tuple with two elements, string and string . [] is a tuple with zero elements.

The syntax for an array of strings is string[]

What you likely want is result.data[‘value’] as any[] .

chrisbajorin Avatar

answered Nov 06 ’22 07:11

chrisbajorin

Alternatively to the previous cast syntax options mentioned above, you can also do the following:

var n = (result.data['value']).map((a) => < //.. >); 

Источник

Typescript cast to array

Last updated: Jan 20, 2023
Reading time · 2 min

banner

# Convert an object to an Array in TypeScript

There are three ways to convert an object to an array in TypeScript:

  1. Object.keys() — returns an array containing the object’s keys.
  2. Object.values() — returns an array containing the object’s values.
  3. Object.entries() — returns an array containing key-value pair arrays.
Copied!
const obj = name: 'Bobby', country: 'Chile' >; const keys = Object.keys(obj); console.log(keys); // 👉️ ['name', 'country'] const values = Object.values(obj); console.log(values); // 👉️ ['Bobby', 'Chile'] const entries = Object.entries(obj); console.log(entries); // 👉️ [['name', 'Bobby'], ['country', 'Chile']]

The first example uses the Object.keys method to get an array of the object’s keys.

The method returns an array of strings where the keys of the object are in the same order as provided by a for. in loop.

Copied!
// 👇️️ ['one', 'two'] console.log(Object.keys(one: 1, two: 2>));

You can then iterate over the array of keys as follows.

Copied!
const obj = name: 'Bobby', country: 'Chile' >; const keys = Object.keys(obj) as (keyof typeof obj)[]; console.log(keys); // 👉️ ['name', 'country'] keys.forEach((key) => // 👇️ name Bobby, country Chile console.log(key, obj[key]); >);

# Convert an Object’s values to an Array in TypeScript

You can use Object.values method to convert an object’s values to an array.

Copied!
const obj = name: 'Bobby Hadz', country: 'Chile' >; const values = Object.values(obj); console.log(values); // 👉️ ['Bobby Hadz', 'Chile']

Similarly to the keys method, the values are added to the array in the same order as that provided by a for. in loop.

# Convert an Object’s entries to an Array in TypeScript

Use the Object.entries method to convert an object to an array of key-value pair arrays.

Copied!
const obj = name: 'Bobby Hadz', country: 'Chile' >; // 👇️ const entries: [string, string][] const entries = Object.entries(obj); console.log(entries); // 👉️ [['name', 'Bobby Hadz'], ['country', 'Chile']]

The nested arrays consist of 2 elements — the key and the value.

You can iterate over the array of key-value pairs by using the forEach() method.

Copied!
const obj = name: 'Bobby', country: 'Chile' >; // 👇️ const entries: [string, string][] const entries = Object.entries(obj); console.log(entries); // 👉️ [['name', 'Bobby'], ['country', 'Chile']] entries.forEach(([key, value]) => // 👇️ name Bobby, country Chile console.log(key, value); >);

Notice that we used array destructuring to destructure the key and value from the array.

Here is an example of how array destructuring works.

Copied!
const arr = ['bobby', 'hadz']; const [a, b] = arr; console.log(a); // 👉️ "bobby" console.log(b); // 👉️ "hadz"

We’re basically unpacking the array’s elements into variables. Note that the order is preserved.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Convert Object to/from Array in Typescript

Typescript is a superset of javascript with compile type checking.

In Application development, We used to get the use cases where data was retrieved from REST API/Database in the form of Array/Object, so need to convert this to Object/Array.

Every developer used to get these user cases during development.

Let us see ways to convert Objects to/from Arrays in javascript/Typescript/Angular applications.

First, we will see how the object Array creates is in typescript.

An array of Objects Declaration and Initialization

For example, an array contains model data like the one below.

[  id: 1, name: "Kiran" >,  id: 2, name: "Tom" >,  id: 3, name: "John" >, ];

Next, is to create an interface that represents the data modal.

export interface Emp  id: number; name: string; > const arr: Emp[] = [  id: 1, name: "Kiran" >,  id: 2, name: "Tom" >,  id: 3, name: "John" >, ];

How to convert Object to Array Typescript Example

This section will see how we can convert Objects to Array in Angular and Typescript with examples.

Typescript Code

Let us assume that you have an object declared with multiple properties.

First Get the named keys using object.keys() method.

This method retrieves keys from the given object and returns an array of keys.

Using the map() method with a defined callback. And callback is executed for each element of an object.

var employees =  kiran:  age: 30, salary: 10000 >, john:  age: 35, salary: 15000 >, Tom:  age: 21, salary: 5000 >, >; let arr = []; Object.keys(employees).map(function (key)  arr.push(< [key]: employees[key] >); return arr; >); console.log("Object=", employees); console.log("Array=", arr);

Typescript Object to Array with Example

Angular Code

For example, object data contains the following properties.

let empdata =  name: "Kiran", age: 30, salary: 10000, >;

First Create an Interface that represents the above.

export interface Emp  name: string; age: number; salary: number; >

In the Component, Create an empty array.

Add the object to an array using the push method

This pushes objects to array and output are

0:name: "kiran", age: 45, salary: 2000> length:1

If you want to convert object properties — name, age, salary

let emp =  name: "kiran", age: 45, salary: 2000, >; let array = []; for (let key in emp)  if (emp.hasOwnProperty(key))  array.push(emp[key]); > > console.log(array);

There are many ways we can do a conversion depending on the object structure.

using Array Push method example

Declared object and empty array using the array push method. we can convert to Array.

let myObject =  name: "kiran", age: 45, salary: 2000, >; let myArray = []; myArray.push(myObject); console.log(myArray);
Array(1)0: name: "kiran", age: 45, salary: 2000>length: 1__proto__: Array(0)

using Spread Operator and Object.assign() method example

we can convert array objects to Single objects.

var array = [ Kiran: "30" >,  Tom: "50" >], object = Object.assign(<>, . array); console.log(object);

Conclusion

To Sum up, Learned to Convert objects to/from Arrays in Typescript with examples.

Источник

How to cast to array in TypeScript 2?

I had some code that cast an object to type array (so I could use array functions on the object without compile errors).

 var n = (result.data['value'] as []).map( (a)=>< //.. >); 

But on upgrade to ts2, I get:

error TS1122: A tuple type element list cannot be empty.

Which is actually a syntax error, claiming you forgot a comma or value. So, how do I modify this cast to work correctly?

I tried as [IMyType] and it worked, but I’d prefer not to specify type since I only need the array.prototype functions here. also, I don’t think that’s how you actually do it.

FlavorScape

People also ask

There are 4 possible conversion methods in TypeScript for arrays: let x = []; //any[] let y1 = x as number[]; let z1 = x as Array; let y2 = x; let z2 = x; The as operator’s mostly designed for *. tsx files to avoid the syntax ambiguity.

Converting a variable from one type to another is possible with type casting in Typescript. Type casting in TypeScript can be done with the ‘as’ keyword or the ‘<>‘ operator.

3 Answers

For some reason the compiler thinks that result.data[‘value’] is a tuple and not an array.

You can cast it like this:

Which should tell the compiler that it’s an array, or:

If your array has only items of type IMyType then simply:

result.data['value'] as IMyType[] 

However, if your array contains items of different types then it’s either a any[] or a tuple, for example:

result.data['value'] as [IMyType, string, string] 

In any case, in the compiled js it will be an array, but tuples let you define a fixed length arrays with specific types.

Nitzan Tomer Avatar

answered Nov 06 ’22 06:11

Nitzan Tomer

You’re not casting to an array.

[string] is a tuple with a single element string . [string, string] is a tuple with two elements, string and string . [] is a tuple with zero elements.

The syntax for an array of strings is string[]

What you likely want is result.data[‘value’] as any[] .

chrisbajorin Avatar

answered Nov 06 ’22 07:11

chrisbajorin

Alternatively to the previous cast syntax options mentioned above, you can also do the following:

var n = (result.data['value']).map((a) => < //.. >); 

Источник

How to cast to array in TypeScript 2?

For some reason the compiler thinks that result.data[‘value’] is a tuple and not an array.

You can cast it like this:

Which should tell the compiler that it’s an array, or:

If your array has only items of type IMyType then simply:

result.data['value'] as IMyType[] 

However, if your array contains items of different types then it’s either a any[] or a tuple, for example:

result.data['value'] as [IMyType, string, string] 

In any case, in the compiled js it will be an array, but tuples let you define a fixed length arrays with specific types.

Solution 2

You’re not casting to an array.

[string] is a tuple with a single element string . [string, string] is a tuple with two elements, string and string . [] is a tuple with zero elements.

The syntax for an array of strings is string[]

What you likely want is result.data[‘value’] as any[] .

Solution 3

Alternatively to the previous cast syntax options mentioned above, you can also do the following:

var n = (result.data['value']).map((a) => < //.. >); 

Arrays in TypeScript

Typescript Essentials #21 - Arrays | Splice

TypeScript || Array extension methods | filter, find, findIndex, forEach, join, keys, map, pop, push

How to push an object into an array and Loop with typescript

Live - Converting to Typescript - Arrays

TypeScript Tutorial #4 - Objects & Arrays

Multidimensional Arrays in TypeScript | Arrays of Arrays in TypeScript

TypeScript Part9- Arrays in TypeScript

ES6 & TypeScript căn bản - Bài 25: Kiểu Array và Tuples

Converting JavaScript to Typescript - Arrays

TypeScript Array Tutorial with Examples

FlavorScape

Listen to the album, Bitwize Operata Now! Music Videos: Decompiled A song about the development industry Rigid Body Physics learn how to make a rigid body physics engine I make drawings. Lots of drawings. See them here: ForeverScape.com Gihub: https://github.com/ForeverScape

Updated on January 10, 2020

Comments

I had some code that cast an object to type array (so I could use array functions on the object without compile errors).

 var n = (result.data['value'] as []).map( (a)=>< //.. >); 

Which is actually a syntax error, claiming you forgot a comma or value. So, how do I modify this cast to work correctly? I tried as [IMyType] and it worked, but I’d prefer not to specify type since I only need the array.prototype functions here. also, I don’t think that’s how you actually do it.

I mean, I could cast it to my final type [IWhatever] but I don’t feel that’s necessary here, I just want to use the array methods.

Источник

Читайте также:  Comment text in python
Оцените статью