TypeScript 中的 String 类型详解
在 TypeScript 中,string 是表示文本数据的原始类型(primitive type),它对应 JavaScript 中的 String 类型。TypeScript 的 string 类型涵盖所有字符串值,包括空字符串、模板字符串等。
1. 基本用法与字面量声明
let username: string = "Alice"; // 普通字符串
let greeting: string = 'Hello'; // 单引号
let message: string = `Welcome`; // 模板字符串(推荐)
// 不同方式声明(效果相同)
const name1: string = "Bob";
const name2 = "Charlie"; // 类型推断为 string(推荐,简洁)
2. 模板字符串(Template Literals)—— ES6+ 强大特性
使用反引号 `,支持多行字符串和表达式插值。
let user: string = "Eve";
let age: number = 28;
let info: string = `用户名: ${user}
年龄: ${age}
状态: ${age >= 18 ? "成年" : "未成年"}`;
// 多行字符串
let html: string = `
<div>
<h1>${user}</h1>
<p>年龄:${age}</p>
</div>
`;
console.log(info);
TS 会自动将模板字符串推断为 string 类型。
3. 字符串常用方法(TS 提供完整类型提示)
所有 JavaScript 字符串方法在 TS 中都有精确的类型定义,使用时有智能补全。
| 方法 | 描述 | 示例结果 |
|---|---|---|
length | 字符串长度 | "hello".length → 5 |
toUpperCase() / toLowerCase() | 大小写转换 | "Hello".toUpperCase() → "HELLO" |
trim() / trimStart() / trimEnd() | 去除空白 | " hi ".trim() → "hi" |
substring(start, end) | 截取子串 | "TypeScript".substring(0, 4) → "Type" |
slice(start, end) | 截取(支持负索引) | "TS".slice(-2) → "TS" |
indexOf(sub) / lastIndexOf(sub) | 查找位置 | "hello".indexOf("l") → 2 |
includes(sub) | 是否包含 | "TS".includes("S") → true |
startsWith() / endsWith() | 开头/结尾判断 | "file.ts".endsWith(".ts") → true |
replace(search, replacement) | 替换(默认只替换第一个) | "a b a".replace("a", "x") → "x b a" |
replaceAll(search, replacement) | 替换所有(ES2021+) | "a a a".replaceAll("a", "x") → "x x x" |
split(separator) | 分割为数组 | "a,b,c".split(",") → ["a","b","c"] |
charAt(index) / charCodeAt(index) | 获取字符/编码 | "TS"[0] → "T"(推荐用 [index]) |
4. 字符串字面量类型(Literal Types)—— TS 强大特性
可以将具体字符串值作为类型,使用场景非常广泛(如状态、方向、事件类型等)。
type Direction = "up" | "down" | "left" | "right";
let move: Direction = "up"; // 只能赋值这四个值之一
// move = "diagonal"; // 错误!
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
let method: HttpMethod = "GET";
type Status = "success" | "error" | "loading";
let state: Status = "loading";
5. 字符串类型操作(高级)
- 联合类型:
let id: string | number = "123";
id = 456; // OK
- 模板字面量类型(Template Literal Types,TS 4.1+):
type EventName = `on${"click" | "hover" | "focus"}`;
// 等价于 "onclick" | "onhover" | "onfocus"
type API = `https://${"api" | "admin"}.example.com`;
// "https://api.example.com" | "https://admin.example.com"
6. 类型转换与检查
// 数字转字符串
let num: number = 42;
let str1: string = num.toString();
let str2: string = String(num);
let str3: string = `${num}`; // 推荐模板字符串
// 其他类型转字符串
let bool: boolean = true;
let strBool: string = bool.toString(); // "true"
// 类型守卫中使用
function logValue(value: string | number) {
if (typeof value === "string") {
// value 被缩小为 string
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
7. 最佳实践建议
| 建议 | 说明 |
|---|---|
| 优先使用模板字符串 | 可读性强,支持插值和多行 |
常量字符串使用 const | const API_URL = "https://api.example.com"; |
| 状态/选项使用字面量类型 | 提升类型安全,避免拼写错误 |
避免 new String() | 创建包装对象,不推荐(用字面量) |
使用 includes / startsWith 等现代方法 | 更清晰 |
开启 strictNullChecks | 防止意外的 null/undefined 字符串操作 |
小结:string 类型速查
| 类型 | 表示内容 | 示例 |
|---|---|---|
string | 所有文本数据 | "hello", 'TS', `template` |
| 字面量类型 | 具体字符串值 | "success" | "error" |
| 模板字面量类型 | 动态生成字符串类型 | `on${Capitalize<Event>}` |
如果您想深入了解字符串模板字面量类型、正则表达式与字符串、国际化(i18n),或者需要实际应用示例(如表单验证、API 路径构建),请告诉我!