gpt4 book ai didi

typescript - 类型 `{ [key in string]: boolean };` 和 `{ [key : string]: boolean };` 是否等效?

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:31 26 4
gpt4 key购买 nike

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 }; 是什么意思?

最佳答案

确实可以观察到一些差异,正如您所展示的,如下所示

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

关于typescript - 类型 `{ [key in string]: boolean };` 和 `{ [key : string]: boolean };` 是否等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56960841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com