基本数据类型 #

一、类型概述 #

Deno使用TypeScript类型系统,提供了丰富的数据类型。基本数据类型(原始类型)包括:string、number、boolean、null、undefined、symbol和bigint。

二、string类型 #

2.1 字符串声明 #

typescript
const single: string = 'Hello';
const double: string = "World";
const template: string = `Hello, ${single}!`;

console.log(template); // Hello, Hello!

2.2 模板字符串 #

typescript
const name = "Deno";
const version = 2.0;

const message = `
Deno信息:
- 名称: ${name}
- 版本: ${version}
- 时间: ${new Date().toLocaleDateString()}
`;

console.log(message);

2.3 标签模板 #

typescript
function highlight(strings: TemplateStringsArray, ...values: unknown[]): string {
  return strings.reduce((result, str, i) => {
    const value = values[i] !== undefined ? `[${values[i]}]` : '';
    return result + str + value;
  }, '');
}

const name = "Deno";
const version = 2.0;

console.log(highlight`Hello ${name}, version ${version}`);
// Hello [Deno], version [2]

2.4 常用方法 #

typescript
const str = "Hello, Deno!";

// 长度
console.log(str.length); // 12

// 访问字符
console.log(str[0]); // H
console.log(str.charAt(0)); // H

// 查找
console.log(str.indexOf("Deno")); // 7
console.log(str.includes("Deno")); // true
console.log(str.startsWith("Hello")); // true
console.log(str.endsWith("!")); // true

// 截取
console.log(str.slice(0, 5)); // Hello
console.log(str.substring(7, 11)); // Deno

// 分割
console.log(str.split(", ")); // ["Hello", "Deno!"]

// 大小写
console.log(str.toUpperCase()); // HELLO, DENO!
console.log(str.toLowerCase()); // hello, deno!

// 去除空白
const padded = "  hello  ";
console.log(padded.trim()); // "hello"
console.log(padded.trimStart()); // "hello  "
console.log(padded.trimEnd()); // "  hello"

// 替换
console.log(str.replace("Deno", "World")); // Hello, World!
console.log(str.replaceAll("o", "0")); // Hell0, Den0!

// 重复
console.log("ab".repeat(3)); // ababab

// 填充
console.log("5".padStart(3, "0")); // 005
console.log("5".padEnd(3, "0")); // 500

三、number类型 #

3.1 数字声明 #

typescript
const integer: number = 42;
const float: number = 3.14;
const hex: number = 0xff; // 255
const binary: number = 0b1010; // 10
const octal: number = 0o755; // 493
const scientific: number = 1e5; // 100000

console.log(integer, float, hex, binary, octal, scientific);

3.2 特殊数值 #

typescript
// Infinity
console.log(Infinity); // Infinity
console.log(1 / 0); // Infinity

// -Infinity
console.log(-Infinity); // -Infinity
console.log(-1 / 0); // -Infinity

// NaN (Not a Number)
console.log(NaN); // NaN
console.log(Number("hello")); // NaN
console.log(Math.sqrt(-1)); // NaN

// 检查NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false

// 检查有限数
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(Infinity)); // false

3.3 数值方法 #

typescript
const num = 3.14159;

// 固定小数位
console.log(num.toFixed(2)); // "3.14"

// 科学计数法
console.log(num.toExponential(2)); // "3.14e+0"

// 精度
console.log(num.toPrecision(4)); // "3.142"

// 转换
console.log(Number.parseInt("42")); // 42
console.log(Number.parseFloat("3.14")); // 3.14
console.log(Number.parseInt("42px")); // 42
console.log(Number.parseInt("px42")); // NaN

3.4 Math对象 #

typescript
// 常量
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045

// 取整
console.log(Math.floor(3.7)); // 3 (向下取整)
console.log(Math.ceil(3.2)); // 4 (向上取整)
console.log(Math.round(3.5)); // 4 (四舍五入)
console.log(Math.trunc(3.7)); // 3 (截断小数)

// 最值
console.log(Math.max(1, 2, 3)); // 3
console.log(Math.min(1, 2, 3)); // 1
console.log(Math.max(...[1, 2, 3])); // 3

// 幂和根
console.log(Math.pow(2, 10)); // 1024
console.log(Math.sqrt(16)); // 4
console.log(Math.cbrt(27)); // 3

// 随机数
console.log(Math.random()); // 0-1之间的随机数
console.log(Math.floor(Math.random() * 10)); // 0-9的随机整数

// 绝对值和符号
console.log(Math.abs(-5)); // 5
console.log(Math.sign(-5)); // -1

// 三角函数
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.cos(0)); // 1

四、boolean类型 #

4.1 布尔值声明 #

typescript
const isTrue: boolean = true;
const isFalse: boolean = false;

console.log(isTrue, isFalse); // true false

4.2 布尔转换 #

typescript
// 使用Boolean函数
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean({})); // true
console.log(Boolean([])); // true

// 使用!!双感叹号
console.log(!!1); // true
console.log(!!0); // false

4.3 假值(Falsy) #

以下值转换为布尔值时为 false

typescript
const falsyValues = [
  false,
  0,
  -0,
  0n,
  "",
  null,
  undefined,
  NaN
];

falsyValues.forEach(value => {
  console.log(Boolean(value)); // 全部为false
});

4.4 逻辑运算 #

typescript
const a = true;
const b = false;

// 与
console.log(a && b); // false

// 或
console.log(a || b); // true

// 非
console.log(!a); // false
console.log(!b); // true

// 空值合并
const value = null ?? "default";
console.log(value); // "default"

// 可选链
const user = { name: "Alice" };
console.log(user?.name); // "Alice"
console.log(user?.address?.city); // undefined

五、null和undefined #

5.1 null #

null 表示"空"或"无值":

typescript
const empty: null = null;

console.log(empty); // null
console.log(typeof empty); // "object" (历史遗留问题)

// 显式设置为空
let user: { name: string } | null = { name: "Alice" };
user = null; // 用户被清空

5.2 undefined #

undefined 表示"未定义"或"缺失":

typescript
const notDefined: undefined = undefined;

console.log(notDefined); // undefined
console.log(typeof notDefined); // "undefined"

// 未赋值的变量
let x: number;
console.log(x); // undefined

// 未传递的参数
function greet(name: string, greeting?: string) {
  console.log(greeting); // undefined(如果未传递)
  return `${greeting ?? "Hello"}, ${name}!`;
}

console.log(greet("Alice")); // Hello, Alice!

5.3 区别 #

typescript
// null: 显式设置为空
const data: string | null = null;

// undefined: 未设置或缺失
let value: string;
console.log(value); // undefined

// 严格相等
console.log(null === undefined); // false
console.log(null == undefined); // true

// 检查
console.log(null === null); // true
console.log(undefined === undefined); // true

5.4 TypeScript严格模式 #

typescript
// 严格模式下,null和undefined是不同的类型
let name: string = "Alice";
// name = null; // 错误:不能将null赋值给string

// 使用联合类型
let nameOrNull: string | null = "Alice";
nameOrNull = null; // 正确

// 使用可选属性
interface User {
  name: string;
  email?: string; // 可能是string或undefined
}

六、symbol类型 #

6.1 创建Symbol #

typescript
const sym1 = Symbol();
const sym2 = Symbol("description");

console.log(sym1); // Symbol()
console.log(sym2); // Symbol(description)

// 每个Symbol都是唯一的
console.log(Symbol() === Symbol()); // false
console.log(Symbol("foo") === Symbol("foo")); // false

6.2 作为属性键 #

typescript
const secretKey = Symbol("secret");

const obj = {
  name: "Alice",
  [secretKey]: "hidden value"
};

console.log(obj.name); // Alice
console.log(obj[secretKey]); // hidden value

// Symbol属性不会出现在常规枚举中
console.log(Object.keys(obj)); // ["name"]
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(secret)]

6.3 全局Symbol注册表 #

typescript
const globalSym1 = Symbol.for("app.id");
const globalSym2 = Symbol.for("app.id");

console.log(globalSym1 === globalSym2); // true

// 获取Symbol的key
console.log(Symbol.keyFor(globalSym1)); // "app.id"

6.4 内置Symbol #

typescript
const obj = {
  [Symbol.iterator]() {
    let i = 0;
    return {
      next: () => ({
        value: i++,
        done: i > 3
      })
    };
  }
};

for (const item of obj) {
  console.log(item); // 0, 1, 2
}

七、bigint类型 #

7.1 创建BigInt #

typescript
const big1: bigint = 9007199254740991n;
const big2: bigint = BigInt("9007199254740991");
const big3: bigint = BigInt(9007199254740991);

console.log(big1); // 9007199254740991n
console.log(big1 === big2); // true

7.2 大数运算 #

typescript
const a = 9007199254740991n;
const b = 1n;

console.log(a + b); // 9007199254740992n
console.log(a * 2n); // 18014398509481982n
console.log(a / 2n); // 4503599627370495n
console.log(a % 2n); // 1n
console.log(a ** 2n); // 81129638414606663681390495662081n

7.3 与Number的区别 #

typescript
// BigInt和Number不能混合运算
const num = 10;
const big = 10n;

// console.log(num + big); // 错误
console.log(Number(big) + num); // 20
console.log(big + BigInt(num)); // 20n

// 类型检查
console.log(typeof 10); // "number"
console.log(typeof 10n); // "bigint"

八、类型检测 #

8.1 typeof操作符 #

typescript
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (历史遗留问题)
console.log(typeof Symbol()); // "symbol"
console.log(typeof 10n); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof (() => {})); // "function"

8.2 instanceof操作符 #

typescript
const arr = [1, 2, 3];
const date = new Date();
const error = new Error("test");

console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
console.log(date instanceof Date); // true
console.log(error instanceof Error); // true

8.3 Array.isArray #

typescript
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("array")); // false
console.log(Array.isArray({ length: 3 })); // false

九、类型别名 #

9.1 基本类型别名 #

typescript
type ID = string;
type Age = number;
type Active = boolean;

const userId: ID = "user-123";
const userAge: Age = 25;
const isActive: Active = true;

9.2 联合类型 #

type

function format(value: StringOrNumber): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

console.log(format("hello")); // HELLO
console.log(format(3.14159)); // 3.14

9.3 字面量类型 #

typescript
type Direction = "up" | "down" | "left" | "right";
type Status = "pending" | "active" | "completed";

function move(direction: Direction): void {
  console.log(`Moving ${direction}`);
}

move("up"); // 正确
// move("forward"); // 错误

十、总结 #

本章学习了:

  • string字符串类型及其方法
  • number数字类型和Math对象
  • boolean布尔类型和逻辑运算
  • null和undefined的区别
  • symbol符号类型
  • bigint大整数类型
  • 类型检测方法
  • 类型别名

下一章,我们将学习类型转换。

最后更新:2026-03-28