想要解析js/ts ast抽象语法树,你会遇到的技术难点和挑战许多,今天就来聊聊这个冒号,光是冒号就可能出目前以下这么多句型中,想要正确识别当前到底是哪一种上下文是一件超级具有挑战性的技术难点
1. 类型注解 (TypeScript)
// 变量类型注解
let name: string = 'John';
// 函数参数和返回值类型
function greet(name: string): void {
console.log(`Hello, ${name}`);
}
// 对象类型注解
interface Person {
name: string;
age: number;
}
// 类型别名
type Point = {
x: number;
y: number;
};
2. 对象字面量属性
const obj = {
key: 'value',
age: 30,
nested: {
prop: true
}
};
3. 三元运算符
const result = condition ? 'true value' : 'false value';
4. 标签语句
outerLoop:
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (i === 5 && j === 5) {
break outerLoop;
}
}
}
5. switch 语句
switch (value) {
case 1:
console.log('One');
break;
case 2:
console.log('Two');
break;
default:
console.log('Other');
}
6. 解构赋值 (TypeScript 中带类型)
// 对象解构
const { name: userName, age: userAge }: { name: string; age: number } = user;
// 数组解构 (TypeScript 4.0+ 元组类型)
const [x, y]: [number, number] = [1, 2];
7. 命名空间 (TypeScript)
namespace MyNamespace {
export class MyClass {}
}
8. 类型断言 (TypeScript)
const someValue: unknown = "this is a string";
const strLength: number = (someValue as string).length;
// 或旧式语法
const strLength2: number = (<string>someValue).length;
9. 条件类型 (TypeScript 高级类型)
type IsString<T> = T extends string ? true : false;
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...