Typescript
- 一、关于Typescript
- 1.什么是Typescript?
- 2.安装 TypeScript
- 二、在 react 中使用 ts 需要注意几点
- 三、ts在react中的使用
- 推荐阅读
一、关于Typescript
TypeScript 是 JavaScript 的一个超集,主要提供了类型系统和对 ES6 的支持。
它的第一个版本发布于 2012 年 10 月,经历了多次更新后,现在已成为前端社区中不可忽视的力量,不仅在 Microsoft 内部得到广泛运用,而且 Google 开发的 Angular 从 2.0 开始就使用了 TypeScript 作为开发语言,Vue 3.0 也使用 TypeScript 进行了重构。
1.什么是Typescript?
- TypeScript 是添加了类型系统的 JavaScript,适用于任何规模的项目。
- TypeScript 是一门静态类型、弱类型的语言。
- TypeScript 是完全兼容 JavaScript 的,它不会修改 JavaScript 运行时的特性。
- TypeScript 可以编译为 JavaScript,然后运行在浏览器、Node.js 等任何能运行 JavaScript 的环境中。
- TypeScript 拥有很多编译选项,类型检查的严格程度由你决定。
- TypeScript 可以和 JavaScript 共存,这意味着 JavaScript 项目能够渐进式的迁移到 TypeScript。
- TypeScript 增强了编辑器(IDE)的功能,提供了代码补全、接口提示、跳转到定义、代码重构等能力。
- TypeScript 拥有活跃的社区,大多数常用的第三方库都提供了类型声明。
- TypeScript 与标准同步发展,符合最新的 ECMAScript 标准。、
2.安装 TypeScript
TypeScript 的命令行工具安装方法如下:
npm install -g typescript
我们约定使用 TypeScript 编写的文件以 .ts 为后缀,用 TypeScript 编写 React 时,以 .tsx 为后缀。
二、在 react 中使用 ts 需要注意几点
- 所有用到jsx语法的文件都需要以tsx后缀命名
- 使用组件声明时的Component<P, S>泛型参数声明,来代替PropTypes
- 全局变量或者自定义的window对象属性,统一在项目根下的global.d.ts中进行声明定义
- 对于项目中常用到的接口数据对象,在types/目录下定义好其结构化类型声明
三、ts在react中的使用
1.声明children
interface Props {
children?: React.ReactNode
}
2.声明属性及事件
interface Props {
flag?: Boolean;
arr?: Array<string>;
sum?: Number;
onClick?: (event: MouseEvent<HTMLButtonElement>) => void;
}
3.props对象中用buttonProps对象作为button的属性
interface Props {
buttonProps?: JSX.IntrinsicElements['button']
}
const Container = ({ buttonProps }: Props) => (
<div>
<button {...buttonProps}></button>
</div>
)
4.styles
// utils.d.ts
declare interface StyleProps {
style?: React.CSSProperties
className?: string
}
// Button.tsx
interface ButtonProps extends StyleProps {
label: string
}
const Button = ({ label, ...styleProps }: ButtonProps) => (
<button {...styleProps}>{label}</button>
)
5.refs
const liRef = useRef<HTMLLIElement>(null)
或者:
const valueRef = useRef<number>(0)
6.ts+函数式组件
export interface Props {
defaultCount: number
}
export default function MyCounter({ defaultCount = 0 }: Props): React.ReactElement {
const [count, setCount] = React.useState<number>(defaultCount);
const incrementCount = () => {
setCount(count + 1);
}
return <button onClick={incrementCount}>Example - count: {count}</button>
}
7.ts+类组件
interface Props {
value: number
}
interface State {
text: string
}
class MyComponent extends React.Component<Props, State> {
static defaultProps: Props = {
value: 0
}
state: State = { text: 'Example' }
render() {
return <div>Syntax {this.props.value} {this.state.text}</div>
}
}