跳至主内容
版本:当前版本

使用 TypeScript

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

TypeScript 是一门通过添加类型定义来扩展 JavaScript 的语言。新建的 React Native 项目默认采用 TypeScript,同时也支持 JavaScript 和 Flow。

TypeScript 入门指南

通过 React Native CLI 创建的新项目,或使用 Ignite 等流行模板时,默认都会采用 TypeScript。

Expo 同样支持 TypeScript,它维护了 TypeScript 模板,或在项目中添加 .ts.tsx 文件时会自动提示你安装配置 TypeScript。

shell
npx create-expo-app --template

在现有项目中添加 TypeScript

  1. 为项目添加 TypeScript、类型声明和 ESLint 插件:
shell
npm install -D typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
备注

该命令会安装所有依赖的最新版本。可能需要调整版本号以匹配项目现有依赖。可使用 React Native Upgrade Helper 查看 React Native 内置的版本。

  1. 添加 TypeScript 配置文件:在项目根目录创建 tsconfig.json
tsconfig.json
{
"extends": "@react-native/typescript-config"
}
  1. 将 JavaScript 文件重命名为 *.tsx 后缀
警告

请保持 ./index.js 入口文件不变,否则生产环境打包时可能遇到问题。

  1. 运行 tsc 命令对新 TypeScript 文件进行类型检查
shell
npx tsc

使用 JavaScript 替代 TypeScript

React Native 新建项目默认采用 TypeScript,但仍可使用 JavaScript。.jsx 后缀的文件会被视为 JavaScript 而非 TypeScript,不会进行类型检查。JavaScript 模块与 TypeScript 模块仍可互相导入。

TypeScript 在 React Native 中的工作原理

开箱即用,TypeScript 源码会在打包时通过 Babel 转换。建议仅将 TypeScript 编译器用于类型检查,这也是新建项目中 tsc 的默认行为。若要将现有 TypeScript 代码迁移到 React Native,使用 Babel 替代 TypeScript 编译器时有一两个注意事项

React Native + TypeScript 示例

通过 React.Component<Props, State> 可为 React 组件的 PropsState 提供接口定义,从而在使用 JSX 操作组件时获得类型检查和编辑器自动补全。

components/Hello.tsx
import {useState} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';

export type Props = {
name: string;
baseEnthusiasmLevel?: number;
};

function Hello({name, baseEnthusiasmLevel = 0}: Props) {
const [enthusiasmLevel, setEnthusiasmLevel] = useState(
baseEnthusiasmLevel,
);

const onIncrement = () =>
setEnthusiasmLevel(enthusiasmLevel + 1);
const onDecrement = () =>
setEnthusiasmLevel(
enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0,
);

const getExclamationMarks = (numChars: number) =>
numChars > 0 ? Array(numChars + 1).join('!') : '';

return (
<View style={styles.container}>
<Text style={styles.greeting}>
Hello {name}
{getExclamationMarks(enthusiasmLevel)}
</Text>
<View>
<Button
title="Increase enthusiasm"
accessibilityLabel="increment"
onPress={onIncrement}
color="blue"
/>
<Button
title="Decrease enthusiasm"
accessibilityLabel="decrement"
onPress={onDecrement}
color="red"
/>
</View>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
greeting: {
fontSize: 20,
fontWeight: 'bold',
margin: 16,
},
});

export default Hello;

可在 TypeScript playground 中进一步探索语法。

实用资源推荐

在 TypeScript 中使用自定义路径别名

要使自定义路径别名在 TypeScript 中生效,需同时配置 Babel 和 TypeScript:

  1. 编辑 tsconfig.json 配置自定义路径映射。设置 src 根目录下的文件可直接访问,并通过 tests/File.tsx 格式访问测试文件:
diff
{
- "extends": "@react-native/typescript-config"
+ "extends": "@react-native/typescript-config",
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "*": ["src/*"],
+ "tests": ["tests/*"],
+ "@components/*": ["src/components/*"],
+ },
+ }
}
  1. babel-plugin-module-resolver 作为开发依赖添加到项目:
shell
npm install --save-dev babel-plugin-module-resolver
  1. 最后配置 babel.config.js(注意 babel.config.js 的语法与 tsconfig.json 不同):
diff
{
presets: ['module:metro-react-native-babel-preset'],
+ plugins: [
+ [
+ 'module-resolver',
+ {
+ root: ['./src'],
+ extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
+ alias: {
+ tests: ['./tests/'],
+ "@components": "./src/components",
+ }
+ }
+ ]
+ ]
}