What are the differences between the private keyword and private fields in TypeScript?

Private keyword The private keyword in TypeScript is a compile time annotation. It tells the compiler that a property should only be accessible inside that class: class PrivateKeywordClass { private value = 1; } const obj = new PrivateKeywordClass(); obj.value // compiler error: Property ‘value’ is private and only accessible within class ‘PrivateKeywordClass’. However compile … Read more

Can I set a private class field using a variable as identifier? How?

No, this doesn’t look to be possible. From the proposal FAQ: Why doesn’t this[‘#x’] access the private field named #x, given that this.#x does? This would complicate property access semantics. Dynamic access to private fields is contrary to the notion of ‘private’. E.g. this is concerning: class Dict extends null { #data = something_secret; add(key, … Read more

What are “class fields” in JavaScript?

Simply put, the reason to use this is ease of understanding the code. Without class field declarations, you would do something like: class Person { constructor() { this.firstName = “Mike”; this.lastName = “Patel”; this.getName = () => { return this.firstName + ” ” + this.lastName; }; } } var p = new Person(); console.log(p.firstName); // … Read more

How do I make a “public static field” in an ES6 class?

You make “public static field” using accessor and a “static” keyword: class Agent { static get CIRCLE() { return 1; } static get SQUARE() { return 2; } } Agent.CIRCLE; // 1 Looking at a spec, 14.5 — Class Definitions — you’d see something suspiciously relevant 🙂 ClassElement[Yield] :   MethodDefinition[?Yield]   static MethodDefinition[?Yield] ; So from … Read more

What is the difference between class method vs. class field function vs. class field arrow function?

There are differences between all 3 versions. This differences are in 3 areas: Who is this at runtime Where the function is assigned What is the type of this in typescript. Lets start with where they work just the same. Consider this class, with a class field: class Greeter { constructor(private x: string) { } … Read more

What is the difference between using constructor vs state = {} to declare state in react component?

They are roughly equivalent. The significant difference is that the initializer in the second example is executed before constructor. The second approach uses class fields proposal. It is not a part of ECMAScript standard yet so you need to set up transpiler properly to use the second approach. UPD Take a look at Babel output … Read more