有一段时间尝试使用flow在react组件上键入属性,其中属性可以是枚举或对象 .
似乎当我在可以具有多个类型(union)的可选属性之后使用 {...spread}
作为属性时,流始终声明它们是不兼容的 .
我们的想法是允许属性是枚举的字符串值,或者值的类型必须是枚举的对象 .
如果将 {...spread}
放置在属性之前,它确实有效,但这不是所需的功能 .
例如(Try Flow):
/* @flow */
import React from 'react';
type _TextAlign = 'left' | 'center' | 'right';
type TextAlign = _TextAlign | { [key: string]: _TextAlign };
type Props = { textAlign?: TextAlign }
const CStr = (props: Props) => <div textAlign="center" {...props} />;
给
8: type Props = { textAlign?: TextAlign }
^ object type [1] is incompatible with string [2].
1 回答
查看
Props
类型的一些可能值:{ 'textAlign': 'left' }
{ 'textAlign': { 'a': 'right', 'b': 'center' }
所以当你到达这个部分时:
您收到错误,因为
{ 'a': 'right', 'b': 'center' }
不是字符串,而不是textAlign
的有效值 .您可以将所有可能的值构建为具有键和值的类型:
但这实际上与以下相同:
如果您随后允许任何其他键,则指定可选
'textAlign'
键没有任何好处 .