![](/img/trans.png)
[英]How to fix Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
[英]How to type a built-in function in an interface?
我有一個 Locale 接口,它定義了一個語言環境,即我的組件的 State:
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
}
在調試代碼時,我正在使用.toSource()
,一個內置的 function 允許在警報上可視化對象內容:
alert(locale.toSource())
警報有效,但 React+tsx 拋出錯誤:
Property 'toSource' does not exist on type 'Locale'
我嘗試將 toSource 輸入為toSource
:
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
toSource: function;
}
但是,它會引發Unexpected error: Cannot find name 'function'.ts(2304)
。
我該怎么做呢?
你可以這樣寫:
type toSourceType = (blahblah?: any) => string;
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
toSource: toSourceType;
}
並且還可以將該類型寫入單獨的type
以進行漂亮的抽象。
感謝在評論中回答的人。 要在 typescript 中使用 function,正確的方法是() => <return type>
而不是function
關鍵字。
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
toSource: () => void; //void if function return nothing.
}
如果 function 什么都不返回,或者正確的類型(如string
或它的number
)返回,則使用void
,或者如果您不確定,則使用unknown
。
希望它會奏效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.