使用 TypeScript
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
TypeScript 是一门通过添加类型定义来扩展 JavaScript 的语言。新建的 React Native 项目默认采用 TypeScript,同时也支持 JavaScript 和 Flow。
TypeScript 入门指南
通过 React Native CLI 创建的新项目,或使用 Ignite 等流行模板时,默认都会采用 TypeScript。
Expo 同样支持 TypeScript,它维护了 TypeScript 模板,或在项目中添加 .ts 或 .tsx 文件时会自动提示你安装配置 TypeScript。
npx create-expo-app --template
在现有项目中添加 TypeScript
- 为项目添加 TypeScript、类型声明和 ESLint 插件:
- npm
- Yarn
npm install -D @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
yarn add --dev @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
该命令会安装所有依赖的最新版本。可能需要调整版本号以匹配项目现有依赖。可使用 React Native Upgrade Helper 查看 React Native 内置的版本。
- 添加 TypeScript 配置文件:在项目根目录创建
tsconfig.json
{
"extends": "@tsconfig/react-native/tsconfig.json"
}
- 将 JavaScript 文件重命名为
*.tsx后缀
应保留
./index.js入口文件不变,否则生产环境打包时可能遇到问题
- 运行
tsc命令对新 TypeScript 文件进行类型检查
- npm
- Yarn
npx tsc
yarn 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 组件的 Props 和 State 提供接口定义,从而在使用 JSX 操作组件时获得类型检查和编辑器自动补全。
import React from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
export type Props = {
name: string;
baseEnthusiasmLevel?: number;
};
const Hello: React.FC<Props> = ({
name,
baseEnthusiasmLevel = 0,
}) => {
const [enthusiasmLevel, setEnthusiasmLevel] = React.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:
- 编辑
tsconfig.json配置自定义路径映射。设置src根目录下的文件可直接访问,并通过tests/File.tsx格式访问测试文件:
{
- "extends": "@tsconfig/react-native/tsconfig.json"
+ "extends": "@tsconfig/react-native/tsconfig.json",
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "*": ["src/*"],
+ "tests": ["tests/*"],
+ "@components/*": ["src/components/*"],
+ },
+ }
}
- 将
babel-plugin-module-resolver作为开发依赖添加到项目:
- npm
- Yarn
npm install --save-dev babel-plugin-module-resolver
yarn add --dev babel-plugin-module-resolver
- 最后配置
babel.config.js(注意babel.config.js的语法与tsconfig.json不同):
{
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",
+ }
+ }
+ ]
+ ]
}