【问题标题】:TypeScript saying a string is invalid even though it's in the union?TypeScript 说一个字符串是无效的,即使它在联合中?
【发布时间】:2020-10-07 12:10:31
【问题描述】:

我从 AWS Amplify 教程中复制了以下内容:

const styles = {
  container: { flexDirection: 'column' },
  ...
};

<div style={styles.container}>

但我得到了:

Type '{ flexDirection: string; }' is not assignable to type 'CSSProperties'.
  Types of property 'flexDirection' are incompatible.
    Type 'string' is not assignable to type '"column" | "inherit" | "-moz-initial" | "initial" | "revert" | "unset" | "column-reverse" | "row" | "row-reverse" | undefined'.

我可以通过将样式内联来轻松解决这个问题,但我很好奇 TypeScript 为何认为这是一个错误。这是一个非常基本的示例,我很惊讶 TS 在它上面失败了,所以这让我对使用 TS 保持警惕。

【问题讨论】:

  • 如果它是有角度的,那么这应该是语法&lt;div [style]="styles.container"&gt;
  • 这是 React,添加到问题
  • 房产为flex-direction: column请查收
  • @CharlesBamford 否,因为该问题中的作者明确将文字转换为string。在我的演员阵容中,TS 将styles.container.flexDirection 的类型推断为string,而不是文字'column'。我不知道为什么它不将其视为文字

标签: javascript reactjs typescript


【解决方案1】:

试试这个

const styles: { container: React.CSSProperties} = {
    container: { flexDirection: 'column' }
};

【讨论】:

  • 所以styles: { [key: string]: React.CSSProperties } 也可以工作,如果有很多属性,它会更短,但我不明白为什么我需要显式转换它
【解决方案2】:

这是一个TS Playground 说明问题和四种可能的解决方案:

type FlexDirection = "column" | "inherit" | "-moz-initial" | "initial" | "revert" | "unset" | "column-reverse" | "row" | "row-reverse" | undefined;

type Styles = {
    container: {
        flexDirection: FlexDirection
    }
}

function doStuff(a: Styles) { }

const stylesDoesNotWork = {
    container: { flexDirection: 'column' }
};

const stylesWithCast = {
  container: { flexDirection: 'column' as 'column' }
}

const stylesFieldConst = {
    container: { flexDirection: 'column' } as const
};

const stylesConst = {
    container: { flexDirection: 'column' }
} as const;

doStuff(stylesDoesNotWork);
doStuff(stylesWithCast);
doStuff(stylesFieldConst);
doStuff(stylesConst);

默认情况下,TypeScript 将为您声明的对象推断类型 string。您可能会在某处对其进行变异并更改值,在这种情况下,文字类型将不正确。所以修复它的基本选项是:

  • 手动注释变量,以便 TypeScript 不会推断字符串。
  • 添加 as 'column' 强制转换以告诉 TypeScript 使用文字类型。
  • 在字段或整个对象上使用 as const 告诉 TypeScript 该字段不允许更改,这允许 Typescript 推断文字值。

【讨论】:

  • > 您可能在某处对其进行了变异并更改了值,在这种情况下,文字类型将不正确。现在这很有意义,谢谢!
  • 如果你在某处改变它并改变它的值,打字稿在它被改变的地方抱怨不是有意义吗?为什么在这里抱怨值是正确的并且是允许的值之一?
猜你喜欢
  • 2021-11-06
  • 2020-08-16
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2019-10-14
相关资源
最近更新 更多