【问题标题】:Flow Types: Field between square brackets流类型:方括号之间的字段
【发布时间】:2019-12-15 23:29:17
【问题描述】:

在流类型中:

export type GroupType = {
  options: OptionsType,
  [string]: any,
};

[string]: any 是什么意思?

编辑:

感谢您的回复。

我该如何理解这段代码?

import type { GroupType } from './types';
const formatGroupLabel = (group: GroupType): string => group.label;

对我来说formatGroupLabel 是一个以group 为参数并返回group.label 的函数。但是我不明白为什么(group: GroupType)前面有: string。可能与我的第一个问题没有链接。

【问题讨论】:

  • 更新了我的答案,但我认为这应该是一个不同的问题。

标签: javascript typescript types flowtype


【解决方案1】:

它是一个索引属性,这意味着如果你尝试获取一个键为string的属性,则值将是any类型。 Documentation

这样使用它以避免混淆是很常见的(但两种方式都有效):

export type GroupType = {
  options: OptionsType,
  [index: string]: any
};

因此您可以将其用于以下对象:

/** @type {GroupType} */
var type = {
  options: {},
  a: 1,
  b: "foo",
  c: function fooBar() {}
};

console.log(typeof type["a"]);
console.log(typeof type["b"]);
console.log(typeof type["c"]);

对于第二部分,const formatGroupLabel = (group: GroupType): string => group.label; 是一个接受GroupType 的函数,返回一个string,它的主体是return group.label。它将在 JavaScript 中具有以下格式:

/** @type {(group: GroupType) => string} */
const formatGroupLabel = (group) => {
  return group.label;
};

【讨论】:

    猜你喜欢
    • 2011-03-06
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多