类型{{字符串中的键:布尔};和类型{{字符串中的键:布尔};”是否等效?

时间:2019-07-09 21:39:55

标签: typescript

react-select中,我偶然发现了那条线

export type SelectComponentsProps = { [key in string]: any };

我从 here

type Keys = 'option1' | 'option2';
type Flags = { [K in Keys]: boolean };

等同于

type Flags = {
    option1: boolean;
    option2: boolean;
}

我也知道 here { [key: string]: boolean; };将对此感到满意

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

那么{ [key in string]: boolean };等于{ [key : string]: boolean };吗?

如果不是,{ [key in string]: boolean };是什么意思?

1 个答案:

答案 0 :(得分:3)

确实可以看到一些差异,如下所示

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

还请注意,一种语法接受可选键,但另一种不接受:

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

最后,使用in显然可以进行自我参考,如@types/styled-components/index.d.ts#24所示:

  

// This is "[key in string]" and not "[key: string]" to allow CSSObject to be self-referential