不锈钢网站哪家最专业,网站首页效果图怎么设计,怎么屏蔽2345网址导航,泰安如何选择网站建设type interface总是傻傻分不清~~~ Type Aliases (type)
type 关键字用于为类型定义一个别名。这可以是基本类型、联合类型、元组、数组、函数等。type 定义的类型在编译后的 JavaScript 代码中会被移除#xff0c;不会留下任何运行时的代码。
//联合类型
type StringOrNumbe… type interface总是傻傻分不清~~~ Type Aliases (type)
type 关键字用于为类型定义一个别名。这可以是基本类型、联合类型、元组、数组、函数等。type 定义的类型在编译后的 JavaScript 代码中会被移除不会留下任何运行时的代码。
//联合类型
type StringOrNumber string | number;
type StringOrNumber 1 | 2;//数组类型
type Point number[];//元组类型
type Point [number, number];//函数类型
type Greeter (name: string) void;const myPoint: Point [10, 20];
const greet: Greeter function(name) {console.log(Hello, name);
};Interfaces (interface)
interface 关键字用于定义对象的形状或类的公共结构。它可以包含方法签名、属性和索引签名。接口通常用于对类进行类型检查确保类实现了接口中定义的所有成员。
interface Person {firstName: string;lastName: string;age?: number; // 可选属性
}const person: Person {firstName: John,lastName: Doe,age: 30
};异同 相同 type和interface都可以用来定义对象和函数 都可以实现继承 不同 type 可以声明基本类型、联合类型、元组类型、通过typeof 操作符来声明interface 可以声明合并。 使用场景 1、官方推荐使用 interface其他无法满足需求的情况下用 type。但是因为联合类型和交叉类型是比较常用的所以避免不了大量使用 type 的场景一些复杂类型也需要通过组装后形成类型别名来使用。 2、如果想保持代码统一还是可选择使用 type。通过上面的对比type 其实可涵盖 interface 的大部分场景。 3、对于 React 组件中 props 及 state推荐使用 type这样能够保证使用组件的地方不能随意在上面添加属性。如果有自定义需求可通过 HOC高阶组件二次封装。 4、编写三方库时使推荐使用 interface其更加灵活自动的类型合并可应对未知的复杂使用场景。 Enums (enum)
enum 关键字用于定义枚举类型它是一种特殊的类型用于定义一组命名的常数。枚举成员被赋值为数字从 0 开始递增除非显式地指定一个值。
enum Color {Red,Green,Blue
}const c: Color Color.Green;1.数值枚举
在数值枚举中每个成员默认从 0 开始自动赋值并且每个成员的值依次递增 1。
enum Color {Red,Green,Blue
}// 使用枚举
const favoriteColor: Color Color.Green;
console.log(favoriteColor); // 输出: 2
console.log(Color[2]); // 输出: Green如果你想要手动指定枚举成员的值可以这样做
enum Color {Red 1,Green 2,Blue 3
}const favoriteColor: Color Color.Green;
console.log(favoriteColor); // 输出: 22.字符串枚举
字符串枚举使用花括号 {} 定义并且每个成员必须显式地指定一个字符串值。
enum Color {Red red,Green green,Blue blue
}const favoriteColor: Color Color.Green;
console.log(favoriteColor); // 输出: green
console.log(Color[Green]); // 输出: green3.反向映射
在 TypeScript 的枚举中你可以通过枚举类型本身来访问枚举成员的名称这称为反向映射。这在调试时非常有用因为它允许你通过值快速找到对应的枚举名称。
enum Color {Red,Green,Blue
}console.log(Color[0]); // 输出: Red
console.log(Color[1]); // 输出: Green
console.log(Color[2]); // 输出: Blue