Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a Set in typescript?

I have following code

private readonly direction :any ={
    east : "1",
    west : "2"
}

private readonly validDirections:Set<Object>= new Set(Object.values(this.direction));    

But typescript compiler shows an error saying 'Set' only refers to a type, but is being used as a value here. Also it shows 'values' does not exist in type Object Constructor

 'Set' only refers to a type  values does not exist

I am using typescript 2.1.5.

highlights from tsconfig.json:

 "target": "es6"
"lib": ["dom","es6","es7.object"],

What am i doing wrong here? How to solve this issue?

like image 980
NewtonCode Avatar asked Feb 08 '17 10:02

NewtonCode


People also ask

How do you write a Set in TypeScript?

Use Set type and new keyword to create a Set in typescript. let directions = new Set<string>(); To create a Set with initial values we can pass the values in an array.

Does TypeScript have a Set type?

TypeScript set is a new data structure added in ES6 version of JavaScript. It allows us to store distinct data (each value occur only once) into the List similar to other programming languages. Sets are a bit similar to maps, but it stores only keys, not the key-value pairs.

How do you declare a Set in JavaScript?

You can create a JavaScript Set by: Passing an Array to new Set() Create a new Set and use add() to add values. Create a new Set and use add() to add variables.

How do you iterate Set in TypeScript?

In TypeScript, we can use the forEach() method to loop or iterate over set entries. A Set is a data structure that contains unique entries without duplicates.


1 Answers

You may need to fix your configuration like following:

"lib": ["dom","es2016","es2017.object"],
like image 91
NatNgs Avatar answered Oct 29 '22 15:10

NatNgs