Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is let validators: { [s: string]: StringValidator; } = {}; the same as ...?

Tags:

typescript

The typescript handbook has the following example:

// Validators to use
let validators: { [s: string]: StringValidator; } = {};
validators["ZIP code"] = new ZipCodeValidator();

Is doing:

let validators: { [s: string]: StringValidator; } = {};

The same as:

let validators = {};
validators["s"] = new StringValidator();

If you could elaborate on the details on how the syntax works that would be great.

like image 391
Ole Avatar asked Jun 19 '26 05:06

Ole


2 Answers

Is doing:

let validators: { [s: string]: StringValidator; } = {};

The same as:

let validators = {};
validators["s"] = new StringValidator();

No, let validators: { [s: string]: StringValidator; } = {}; is different from let validators = {};.


What

let validators: { [s: string]: StringValidator; } = {};

is doing is declaring an identifier with a type. What you're saying with the code above is: "I'm declaring the identifier validators and the type of this object can have any string, s as a key to the object (remember that javascript objects are just key-value pairs) and the value of the every key will be of type StringValidator.

If you remove the type annotation (anything on the right side of the :), you not given the object a type.

You can observe the difference when you highlight over the declariation in vs code. You'll get the type { [s: string]: StringValidator; } if you add the type annotation, but if you remove it, you'll get any, meaning that object can be 'any' type.

like image 78
Rico Kahler Avatar answered Jun 21 '26 17:06

Rico Kahler


No, they're not the same.

The first one

let validators: { [s: string]: StringValidator; } = {};

declares a variable named validators whose type is { [s: string]: StringValidator; } and whose value is {}. This type means that validators can be indexed by key (a string) to yield an instance of StringValidator. Note that s is a "dummy" variable whose actual name has no runtime effect; the name serves only to document the meaning of the indexer.

Note that no StringValidator object is instantiated. The final value of validators is an empty object.

The second one

let validators = {};
validators["s"] = new StringValidator();

first declares a variable named validators whose type is inferred to be {} (an object with no properties) and whose value is {}. It then instantiates a StringValidator object and assigns the result to the s property of validators.

The final value of validators is an object with a property named s that references a StringValidator object.

like image 36
Michael Liu Avatar answered Jun 21 '26 19:06

Michael Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!