l-hammer / l-hammer/learning

TS 基础类型

Open
#1 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

typescript
Dominant language
No language data
Stars
1
Forks
0
PR merge metrics
No merged PRs in 30d

Description

布尔(Boolean)

const isDone: boolean = true;

数字(Number)

const decimal: number = 18; // 十进制
const hex: number = 0x12; // 十六进制
const binary: number = 0b1010; // 二进制
const octal: number = 0o22; // 八进制

字符串(String)

const color: string = "blue";

模板字符串

const name: string = `lhammer`;
const sentence: string = `Hello, my name is ${name}`;

数组(Array)

const list: number[] = [1, 2, 3]; // 数字型数组

第二种方式是使用数组泛型:Array<元素类型>

const list: Array<number> = [1, 2, 3];

元祖(Tuple)

类似于JavaScript 中的数组,元祖可以包含任何类型的成员。

let x: [string, number];

x = ["hello", 10]; // ✔️
x = [10, "hello"]; // ❌

x[0].slice(1); // ✔️
x[1].slice(1); // ❌,"number" 不存在`slice`方法

x[1] = true; // ❌,"true" 不能分配给类型 "number"
x[2] = "world"; // ❌,越界元素不存在

枚举(Enum)

枚举类型是对JavaScript 数据类型的一个补充,使用枚举类型可以为一组数值赋予友好的名字。

数字类型枚举
enum Color {
  Red,
  Green = 2,
  Blue
}

let c1: Color = Color.Red; // 0
let c2: Color = Color.Green; // 2
let c3: Color = Color.Blue; // 3

枚举值默认是从 0 开始的索引值,也可手动指定。

其编译后对应的JavaScript如下:

var Color;
(function (Color) {
    Color[Color["Red"] = 0] = "Red";
    Color[Color["Green"] = 2] = "Green";
    Color[Color["Blue"] = 3] = "Blue";
})(Color || (Color = {}));

所以我们可以通过枚举值快速反查到对应的名称,如下所示:

let c3_key: string = Color[3]; // Blue
字符串枚举
enum ErrorTypes {
  ERROR_310 = "用户未登录",
  ERROR_404 = "请求不存在",
  ERROR_502 = "网关异常",
}
const resps = [{ code: 310}, { code: 404}, { code: 502}];

resps.forEach(resp => console.log(ErrorTypes[`ERROR_${resp.code}`]))
常量枚举
enum Weekday {
  Monday,
  Tuseday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}

结合namespace向枚举类型添加静态方法

namespace Weekday {
  export function isBusinessDay(day: Weekday): Boolean {
    switch (day) {
      case Weekday.Saturday:
      case Weekday.Sunday:
        return false;
      default:
        return true;
    }
  }
}

const { Monday, Sunday } = Weekday;

Weekday.isBusinessDay(Monday); // true
Weekday.isBusinessDay(Sunday); // false

Any

any能兼容TypeScript中所有的类型,同时也会跳过类型检测,一般用在我们无法确定变量类型的时候。

let notSure: any = 8;

notSure = "maybe a string instead"; // ✔️
notSure = false; // ✔️

let list: any[] = [1, true, "free"];

list[1] = 100; // ✔️

Void

any 类型相反,void 表示没有类型,一般用在当一个函数没有返回值的时候。

function warnUser(): void {
  console.log("This is my warning message");
}

Null and Undefined

通常情况我们可以把nullundefined 看成是所有类型的子类型,两者都可以赋值给任意类型的变量。

let u: undefined = undefined
let n: null = null

然而,当你设定了 --strictNullChecks 标记,nullundefined 只能赋值给 void 和它们各自,这能避免很多常见的问题。 也许在某处你想传入一个 stringnullundefined,你可以使用联合类型 string | null | undefined

Never

never 表示那些永远不会发生的类型,同时也是所有类型的子类型,可以赋值给任意类型的变量。

常用的几个例子:

const error: never = (() => {
  throw new Error("error");
})();

const loop: never = (() => {
  while (true) {}
})();

Object

object 表示非原始类型,也就是除 numberstringbooleansymbolnullundefined 之外的类型。

使用 object 类型,就可以更好的表示像 Object.create 这样的 API。例如:

declare function create(o: object | null): void;

create({ prop:0 }); // ✔️
create(null); // ✔️

create(42); // ❌
create('string'); // ❌
create(false); // ❌

Refs:
» Basic Types
» 深入理解 TypeScript -- 枚举

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository file, test, or entry point is named; start by locating where this Chinese TypeScript basic-types material is stored and compare it with the linked Basic Types reference. Done is not defined because the issue does not specify a correction, addition, or acceptance check.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.