简体   繁体   中英

react-native - *.js importing *.ts file

How to allow *.js files to import *.ts files in react-native but without rename of any of two files ?

we want to import below src/lib/setGlobalStyle .ts file from the src/App .js

//MIT LICENSE from: https://github.com/Ajackster/react-native-global-props

import React from 'react'
import { StyleProp, ViewStyle } from 'react-native'


export function setGlobalStyle(obj, customProps) {
 const oldRender = obj.prototype.render;
  const initialDefaultProps = obj.prototype.constructor.defaultProps;
  obj.prototype.constructor.defaultProps = {
    ...initialDefaultProps,
    ...customProps,
  }
  obj.prototype.render = function render() {
    let oldProps = this.props;
    this.props = { ...this.props, style: [customProps.style, this.props.style] };
    try {
      return oldRender.apply(this, arguments);
    } finally {
      this.props = oldProps;
    }
  };
}

but below import which is inside App .js only works when we rename the setGlobalStyle .ts file to setGlobalStyle .js :

import * as Utils from './lib/setGlobalStyle'

and of course the setGlobalStyle .ts currently does not contain any TypeScript types, that is because we had to remove all and rename it to .js so we can continue on the project until this gets an answer.

note : the reason why we need TypeScript is to allow IDE autocomplete of the parameters (ie the customProps argument).

JSDoc-support in Javascript allows you to import type definitions directly. I know that's not the same as importing the actual module (but I think that is madness if the type definitions exist):

/**
 * @param {import("./mymodule").customProps } customProps
 */
export function setGlobalStyle(obj, customProps) {
    customProps. // has full auto-completion 

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM