typescript 全局覆盖第三方导出接口

jhkqcmku  于 2023-03-31  发布在  TypeScript
关注(0)|答案(1)|浏览(217)

我使用@react-native-firebase/messaging并调用方法messaging().onNotificationOpenedApp(remoteMessage => ....)
我想覆盖remoteMessage类型中的属性data,这样我就可以在发送通知时使用TS智能感知。
我的data类型应该是这样的:

data: {
  page: PageType
  pageProps: {
    id: string
    ....
  }
}

我尝试在我的项目根文件夹中创建一个global.d.ts

declare global {
  namespace FirebaseMessagingTypes {
    interface RemoteMessage extends MyCustomDataType { }
  }
}

但是这不起作用。我怎样才能全局覆盖这个类型而不需要显式设置函数的属性类型呢?
谢谢=D

bvpmtnay

bvpmtnay1#

定义你自己的使用类型的函数

type MyData = {
  page: string,
  pageProps: string,
}

type MyData2 = {
  age: string,
  name: string,
}

type RemoteMessageWithMyData = Omit<RemoteMessage, 'data'> & {data: MyData}
type RemoteMessageWithSomeOther = Omit<RemoteMessage, 'data'> & {data: MyData2}

function handleMydata(payload: RemoteMessageWithMyData) {
  console.log(payload.data.pageProps)
}

function handleMyOtherdata(payload: RemoteMessageWithSomeOther) {
  console.log(payload.data.age)
}

function isMyOtherDataPayload (rm: RemoteMessage): rm is RemoteMessageWithSomeOther  {
 if (rm.data && 'age' in rm.data) return true
 return false
}

function isMyDataPayload (rm: RemoteMessage): rm is RemoteMessageWithMyData  {
 if (rm.data && 'page' in rm.data) return true
 return false
}

function onNotificationOpenedAppMyData(rm: RemoteMessage) {
  if (isMyDataPayload(rm)) {
   handleMydata(rm)
  } else if (isMyOtherDataPayload(rm)){
    handleMyOtherdata(rm)
  }

}

onNotificationOpenedApp((dafa:RemoteMessage) => onNotificationOpenedAppMyData(dafa))

相关问题