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

React Native CLI初始化项目的App.js为何包含TypeScript代码?

明确答复
  • 你没有创建TypeScript类型的React Native项目
  • 当前项目就是React Native CLI生成的标准JavaScript项目
  • 文件里的类TypeScript语法不会在后续开发中引发编译或运行问题
具体解释

React Native新版本的默认JavaScript模板,会在初始生成的App.js中加入轻量类型标注,你看到的如下代码就是模板自带内容:

import type {Node} from 'react';

const Section = ({children, title}): Node => {
  const isDarkMode = useColorScheme() === 'dark';
  return (
    <View style={styles.sectionContainer}>
      <Text
        style={[
          styles.sectionTitle,
          {
            color: isDarkMode ? Colors.white : Colors.black,
          },
        ]}>
        {title}
      </Text>
      <Text
        style={[
          styles.sectionDescription,
          {
            color: isDarkMode ? Colors.light : Colors.dark,
          },
        ]}>
        {children}
      </Text>
    </View>
  );
};

const App: () => Node = () => {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Header />
        <View
          style={{
            backgroundColor: isDarkMode ? Colors.black : Colors.white,
          }}>
          <Section title="Step One">
            Edit <Text style={styles.highlight}>App.js</Text> to change this
            screen and then come back to see your edits.
          </Section>
          <Section title="See Your Changes">
            <ReloadInstructions />
          </Section>
          <Section title="Debug">
            <DebugInstructions />
          </Section>
          <Section title="Learn More">
            Read the docs to discover what to do next:
          </Section>
          <LearnMoreLinks />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

这些带类型的写法不是TS项目专属:

  • Metro打包器默认支持解析JS文件中的这类类型语法,构建时会自动把所有类型标注、类型导入语句完全剥离,不会打包进最终运行产物
  • 标注的唯一作用是给编辑器提供基础的代码提示,不会开启强制类型校验,写代码时就算不符合类型要求也不会阻断编译
  • 真正的TypeScript RN项目有两个明确判断标准:根目录存在tsconfig.json配置文件、业务代码后缀为.ts/.tsx,你用默认命令初始化的项目不满足这两个条件,属于纯JS项目。
可选操作

如果看不惯这些类型标注,直接全部删掉即可:删掉import type {Node} from 'react';导入语句,移除Section组件、App函数后面的: Node、: () => Node类型标注,代码可以正常运行,不会有任何问题。
后续开发直接按纯JavaScript的习惯写业务代码就行,不需要适配TS规则,这些初始标注不会对开发流程造成任何阻碍。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:51:44