reactjs - 如何在界面中键入内置函数?
问题描述
我有一个 Locale 接口,它定义了一个语言环境,这是我的组件的状态:
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
}
在调试代码时,我正在使用.toSource()
一个内置函数,它允许在警报上可视化对象内容:
alert(locale.toSource())
警报有效,但 React+tsx 抛出错误:
Property 'toSource' does not exist on type 'Locale'
我尝试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
以进行漂亮的抽象。
推荐阅读
- c++ - 'g++' 不是内部或外部命令、可运行程序或批处理文件。
- gps - 如何将 gps 模块的实时位置检索到我的数据库中,以便可以在多个应用程序中使用它?
- prolog - 如何获得所有重复列表元素的组合 - 序言
- php - Laravel belongsTo 和 hasMany 不返回数据
- webpack - Webpack url-loader 对图像 url 进行编码,但会破坏文件路径
- android - 为什么 Fragments 会从它们的 Activity 中分离出来?
- node.js - Uncaught SyntaxError: Unexpected token < for JavaScript files
- android - RecyclerView Android Studio 不显示 Firebase 数据库中的数据
- javascript - 有没有办法让这个反应组件不那么冗长?
- python - 成功合并后 Pandas 返回空 DF