You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义包含返回字符串的函数属性的TypeScript类型?

错误原因

你定义的ContextProps类型中,getToken约定为无参数、返回字符串类型的函数,你之前的两种写法都不满足类型要求:

  • 第一种写法() => {token: string} 存在两处问题:一是大括号会被识别为函数体块作用域,不会作为返回值处理;二是即使调整为返回对象的写法,也和约定的返回字符串类型不匹配。
  • 第二种写法() => text: string属于无效语法,TS不支持这种在返回位置直接标注类型的写法。

正确写法

你只需要让getToken的默认实现返回一个字符串即可,通常默认值可以先用空字符串占位,后续TokenContext.Provider传入的实际实现会覆盖该默认值:

import { createContext } from 'react';

type ContextProps = {
  saveToken: (text: string) => void;
  getToken: () => string;
};

export const TokenContext = createContext<ContextProps>({
  saveToken: (text: string) => {},
  // 符合 () => string 类型约束的实现
  getToken: () => '',
});

实际业务实现示例

在Provider层传入真实的业务逻辑时,写法示例如下:

const App = () => {
  const contextValue = {
    saveToken: (token: string) => localStorage.setItem('user_token', token),
    getToken: () => localStorage.getItem('user_token') || ''
  };

  return (
    <TokenContext.Provider value={contextValue}>
      {/* 你的业务组件 */}
    </TokenContext.Provider>
  )
}

内容的提问来源于stack exchange,提问作者jmnguye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:45:02