跳到主要内容
版本:0.81

使用 TypeScript

TypeScript 是一门通过添加类型定义来扩展 JavaScript 的语言。新的 React Native 项目默认以 TypeScript 为目标,但也支持 JavaScript 和 Flow。

TypeScript 入门

React Native CLI 或流行模板如 Ignite 创建的新项目将默认使用 TypeScript。

TypeScript 也可与 Expo 一起使用,它维护着 TypeScript 模板,或者会在您将 .ts.tsx 文件添加到项目时提示您自动安装和配置 TypeScript。

npx create-expo-app --template

向现有项目添加 TypeScript

  1. 将 TypeScript、类型定义和 ESLint 插件添加到您的项目中。
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 文件。
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 作为开发包添加到您的项目:
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",
+ }
+ }
+ ]
+ ]
}