首页 > 解决方案 > 如何在界面中键入内置函数?

问题描述

我有一个 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).

我该怎么做呢?

标签: reactjstypescript

解决方案


你可以这样写:

type toSourceType = (blahblah?: any) => string;

interface Locale {
  src: string;
  alt: string;
  language: string;
  i18nFormat: string;
  toSource: toSourceType;
}

并且还可以将该类型单独写入type以进行漂亮的抽象。


推荐阅读