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

使用expo-notifications在TypeScript中调用getPermissionsAsync报错求助

Expo Notifications在TypeScript环境中提示getPermissionsAsync未定义的问题

我尝试使用expo-notifications发送推送通知,参考官方文档示例代码,在JavaScript环境下运行正常,但切换到TypeScript环境时出现以下错误:

[Unhandled promise rejection: TypeError: Notifications.getPermissionsAsync is not a function. (In 'Notifications.getPermissionsAsync()', 'Notifications.getPermissionsAsync' is undefined)]

以下是我的代码:

import { StatusBar } from "expo-status-bar";
import { Button, StyleSheet, Text, View, Platform } from "react-native";
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";
import { useEffect, useState } from "react";

// Notifications.setNotificationHandler({
//   handleNotification: async () => ({
//     shouldShowAlert: true,
//     shouldPlaySound: false,
//     shouldSetBadge: false,
//   }),
// });

const sendPushNotification = async (expoPushToken: any) => {
  const message = {
    to: expoPushToken,
    sound: "default",
    title: "Test title",
    body: "Test body",
    data: { testData: "test data" },
  };

  await fetch("https://exp.host/--/api/v2/push/send", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Accept-encoding": "gzip, deflate",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(message),
  });
};
export default function App() {
  const [token, setToken] = useState();

  console.log({ token });

  useEffect(() => {
    let mounted = true;
    if (mounted) {
      (async () => {
        if (Device.isDevice) {
          const { status: existingStatus } = 
            await Notifications.getPermissionsAsync();
          let finalStatus = existingStatus;
          if (existingStatus !== "granted") {
            const { status } = await Notifications.requestPermissionsAsync();
            finalStatus = status;
          }
          if (finalStatus !== "granted") {
            alert("Failed to get push token for push notification!");
            return;
          }
          const { data } = await Notifications.getExpoPushTokenAsync();
          setToken(data as any);
        } else {
          alert("Must use physical device for Push Notifications");
        }

        if (Platform.OS === "android") {
          Notifications.setNotificationChannelAsync("default", {
            name: "default",
            importance: Notifications.AndroidImportance.MAX,
            vibrationPattern: [0, 250, 250, 250],
            lightColor: "#FF231F7C",
          });
        }
      })();
    }

    return () => {
      mounted = false;
    };
  }, []);
  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      {token && (
        <Button onPress={() => sendPushNotification(token)} title="Send" />
      )}
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

可能的原因及解决方法

  • 版本兼容性问题:TypeScript对类型定义要求更严格,旧版本expo-notifications可能存在类型导出不完整或API变更的情况。
    解决:更新到最新稳定版本,执行命令:
    expo install expo-notifications
    
  • TypeScript配置错误:未正确配置Expo与TypeScript的适配,导致模块导出无法被正确识别。
    解决:确保项目根目录有tsconfig.json,并包含Expo基础配置:
    {
      "extends": "expo/tsconfig.base",
      "compilerOptions": {
        "strict": true
      }
    }
    
  • 模块导入解析问题:部分情况下TypeScript无法正确解析通配符导入的全部API,可尝试单独导入所需方法:
    import { getPermissionsAsync, requestPermissionsAsync, getExpoPushTokenAsync, setNotificationChannelAsync, AndroidImportance } from "expo-notifications";
    
  • 缓存干扰:Metro或TypeScript的缓存导致未加载最新模块定义。
    解决:清除缓存后重启项目:
    npx expo start --clear
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:50:23