亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

TypeScript 說一個字符串是無效的,即使它在聯合中?

TypeScript 說一個字符串是無效的,即使它在聯合中?

至尊寶的傳說 2022-10-08 15:14:01
我從 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 保持警惕。
查看完整描述

3 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

這是一個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'cast 以告訴 TypeScript 使用文字類型。

  • 在字段或整個對象上使用as const來告訴 TypeScript 不允許更改字段,這允許 Typescript 推斷文字值。


查看完整回答
反對 回復 2022-10-08
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

嘗試這個


const styles: { container: React.CSSProperties} = {

    container: { flexDirection: 'column' }

};


查看完整回答
反對 回復 2022-10-08
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

導入并使用類型:

import type { Property } from 'csstype'

使用 Property.FlexDirection 指定類型


查看完整回答
反對 回復 2022-10-08
  • 3 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號