yshaojun / blog

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

初学 TypeScript

yshaojun opened this issue · comments

2020年的目标之一是学会 TypeScript,并希望它能像 JS 一样,成为我的主力开发语言,正好在假期学习一下。

带类型的 JS

ts 是 js 的超集,因此任何合法的 js 都是合法的 ts。在 ts 官方文档 里,主要讲的是 类型,并没有 if 语句、函数等语言特性的介绍,说明 ts 基本等同于“带类型的 JS”。

ts 的类型有 基本类型接口(interface) 两大类。

基本类型有12个:

  1. string
  2. number
  3. boolean
  4. null
  5. undefined
  6. void
  7. array
  8. object
  9. tupple
  10. enum
  11. any
  12. never

ts 接口大大扩展了 Java 接口的使用场景,除了被类实现(implements),还可以用来自定义类型,比如定义 LabeledValue

interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

接口的使用主要有如下4个方面:

  1. Object Types(Optional Properties, Readonly properties, Excess Property Checks)
  2. Function Types
  3. Indexable Types
  4. Class Types
  5. Hybrid Types

与其他静态语言比如 C/C++、Java 相比,ts 的类型系统更加丰富强大,可以感受到在约束 JS 的同时,应该不会降低开发效率。

React 中使用 TS

在 React 中使用 ts 需要注意 两点

  1. 文件名必须以 .tsx 为后缀
  2. 开启 jsx 选项

然后,需要在 webpack 的配置里添加 ts-loader,具体可参考 React & Webpack

module: {
  rules: [
    {
      test: /\.ts(x?)$/,
      exclude: /node_modules/,
      use: [
        {
          loader: "ts-loader"
        }
      ]
    }
  ]
}

一个简单的示例代码如下:

import * as React from 'react';
import * as ReactDOM from 'react-dom';

interface AppProps {
  happy: string
}

class App extends React.Component<AppProps, {}> {
  render() {
    return (
      <div className='app'>
        <h1>React-ts</h1>
        <p>{this.props.happy} coding here ~</p>
      </div>
    );
  }
}

ReactDOM.render(<App happy='Happy'/>, document.getElementById('root'));

这里有个有趣的地方:props 的校验不必再使用 prop-types 了,ts 的类型注解不仅能起到相同作用,还更加直观简洁!

感想

一直都知道静态语言的好处,它能够让人在读代码而不运行时,就知道中间某个变量大概长什么样子。还能大大降低 "xxx is undefined" 和 "undefined is not a function" 这种低级错误。但是也想到静态语言限制了灵活性,担心在小功能里反而显得笨重。

经过几天对 ts 的学习,感到 ts 的类型系统比 C/C++、Java 要强大丰富很多,在需要对复杂变量进行注解的时候,基本都能利用 ts 语言特性直接实现,没有其他静态语言里那种“弯弯绕绕”的感觉。总体来说,ts 是一种灵活的静态语言,值得一试!