In react-select I stumbled across the line
export type SelectComponentsProps = { [key in string]: any };
I know from here that
type Keys = 'option1' | 'option2';
type Flags = { [K in Keys]: boolean };
is equivalent to
type Flags = {
option1: boolean;
option2: boolean;
}
I also know from
here
that { [key: string]: boolean; };
will be satisfied by this:
let map : { [key: string]: boolean} = {};
map["foo"] = true;
map["bar"] = false;
map["foobar"] = "foo"; // Throws exception
map[1] = true; // Curiously doesn't throws exception
map.foo = true; // Throws exception
So, is { [key in string]: boolean };
equivalent to { [key : string]: boolean };
?
If not, what does { [key in string]: boolean };
mean?
The {[key: string]: string} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties ahead of time, but know the shape of the values. The index signature in the examples means that when an the object is indexed with a string , it will return a string .
Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings. index.ts. Copied!
In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string.
An Operator is a symbol which operates on a value or data. It represents a specific action on working with data. The data on which operators operates is called operand.
Some differences can be observed indeed, as you showed, and as below
type T1 = {[key: string]: null};
type T2 = {[key in string]: null};
const t1: T1 = {'foo': null, 10: null};
const t2: T2 = {'foo': null, 10: null};
type S1 = keyof T1; // string | number
type S2 = keyof T2; // string
const s1: S1 = 10;
const s2: S2 = 10; // error
TS Playground link
Observe also that one syntax accepts optional keys but not the other:
type T1 = {[key: string]: null};
type T2 = {[key in string]: null};
type T1opt = {[key: string]?: null}; // invalid syntax
type T2opt = {[key in string]?: null};
TS Playground link
Finally, using in
apparently allows for self-reference, as seen in @types/styled-components/index.d.ts#24:
// This is "[key in string]" and not "[key: string]" to allow CSSObject to be self-referential
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With