Tony Bao
Tony Bao

Reputation: 922

Typesrcript typing {[key: string]: any}

I have this function:

validate(formGroup: FormGroup): {[key: string]: any} 

and I can

return {validateLocation: false}

or

return {'validateLocation': false}

key:string shoud be 'validateLocation': false, why both are all working? validateLocation is NOT string, right?

Upvotes: 4

Views: 9246

Answers (2)

Sefe
Sefe

Reputation: 14007

TypeScript is a superset of JavaScript. That means it must maintain a certain level of compatibility with JavaScript. While you are right in principle to expect key access to be in the form 'validateLocation' or "validateLocation", it is necessary also to support the validateLocation syntax for compatibility. That leads to these results:

let validateLocation: string = 'a';

let value1 = {validateLocation: false} //Key will be "validateLocation"
let value2 = {'validateLocation': false} //Key will be "validateLocation"
let value3 = {"validateLocation": false} //Key will be "validateLocation"
let value4 = {[validateLocation]: false} //Key will be "a"

Upvotes: 3

Tim Perry
Tim Perry

Reputation: 13256

Keys in JavaScript objects are always strings. The syntax doesn't require you to specify it, but yes, validateLocation here becomes a string key in both cases.

You can see this with:

var x = { a: 1 };
console.log(x['a']); // Prints 1, because 'a' the string is a valid key.

MDN has more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals.

Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript identifier or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (.) property, but can be accessed and set with the array-like notation("[]").

Upvotes: 3

Related Questions