TypeScript 类型体操——Hello World

123 阅读1分钟

前言

Github 地址:github.com/type-challe…
TypeScript 是趋势,早学晚学,早晚都要学,就以这个练习开始,边练边学,边学边总结。

正文

热身题

Hello World

TS Playground:github.com/type-challe…

13 - Hello World
-------
by Anthony Fu (@antfu) #warm-up

### Question

Hello, World!

In Type Challenges, we use the type system itself to do the assertion.

For this challenge, you will need to change the following code to make the tests pass (no type check errors).


// expected to be string
type HelloWorld = any


// you should make this work
type test = Expect<Equal<HelloWorld, string>>

Click the `Take the Challenge` button to start coding! Happy Hacking!

> View on GitHub: https://tsch.js.org/13

/* _____________ Your Code Here _____________ */

type HelloWorld = any // expected to be a string

/* _____________ Test Cases _____________ */
import type { Equal, Expect, NotAny } from '@type-challenges/utils'

type cases = [
  Expect<NotAny<HelloWorld>>,
  Expect<Equal<HelloWorld, string>>,
]

答案

type HelloWorld = string

总结
类型变量的定义方式有三种,typeinterfaceenum,三者都相当于 JS 中的const,一旦定义就不可改变,区别是:

  • neum仅用来定义枚举类型;
  • interface可用来定义函数、对象、类;
  • type用于绝大多数类型,如普通的值、对象、函数、数组、元组等

TS 的基础类型:

  • 布尔:boolean
  • 数字:number
  • 字符串:string
  • 数组:number[]/Array<number>
  • 元组:[number, string]
  • 枚举:enum Color { RED, GREEN, BLUE }
  • any
  • void
  • nullundefined
  • never
  • object