// 定义一个函数接口interfaceUserGreeter{(user:User):string;}// 实现该函数constgreetUser:UserGreeter=function(user){return`Hello,${user.name}! Your email is${user.email}.`;};// 使用该函数constuser:User={id:1,name:"Alice",email:"alice@example.com"};console.log(greetUser(user));// 输...
interface Point { x: number; y: number; 当我们使用 TypeScript 时,就会用到 `interface` 和 `type`,平时感觉他们用法好像是一样的,没啥区别,都能很好的使用,所以也很少去真正的理解它们之间到底有啥区别。我们开发过经常或这么来定义类型: 1. 2. 3. 4. 5. 6. 7. interface Point { x: number; ...
函数类型定义在interface中可以明确函数的参数类型、返回值类型以及函数的结构。这就像是为函数建立了一个蓝图或者契约,确保在代码中遵循这个契约的函数才能被正确使用。例如,我们可以定义一个interface,其中包含一个函数类型的属性,这个函数可能需要特定类型的参数并且返回特定类型的值。这有助于在大型项目中保持代码的一致...
与interface不同,type还可以用来表示其他的类型,比如基本数据类型、元素、并集等 ⏰interface interface 只能表示Object, Function。 不能表示其它类型 ⏰type //【基本类型】type Name =string;//【类型并集&交叉】type PartialPointX ={x: number} type PartialPointY={y: number}//并集type PartialPoint = P...
interface SquareConfig { color?: string; width?: number; } function createSquare(config: SquareConfig): { color: string; area: number } { let newSquare = { color: "white", area: 100 }; if (config.clor) { // ⚠️⚠️⚠️ Error: Property 'clor' does not exist on type ...
interface A { f(): number; f(x: boolean): boolean; f(x: string, y: string): string; } function MyFunc(): number; function MyFunc(x: boolean): boolean; function MyFunc(x: string, y: string): string; function MyFunc( x?:boolean|string, y?:string ):number|boolean|string { if (...
interface.js 文件代码如下: interfaceShape{name:string;width:number;height:number;color?:string;}functionarea(shape:Shape){vararea=shape.width*shape.height;return"I'm "+shape.name+" with area "+area+" cm squared";}console.log(area({name:"rectangle",width:30,height:15}));console.log(area...
}// 使用 type 定义函数类型typeAddFunction =(x:number, y:number) =>number;// 使用 interface 定义函数类型interfaceSubtractFunction { (x:number,y:number):number; }// 使用 type 组合现有类型typeName =string;typeAge =number;typePerson = {name:Name;age:Age; ...
(容易混淆的 interface 内的小括号) TS 中特有的一些东西 比如typeof,keyof, infer 以及本文要讲的泛型。 「把这些和 JS 中容易混淆的东西分清楚,然后搞懂 TS 特有的东西,尤其是泛型」(其他基本上相对简单),TS 就入门了。 泛型初体验 在强类型语言中,一般而言需要给变量指定类型才能使用该变量。如下代码: ...
class Animal3{ constructor(public name:string){} } interface WithClassName{ new (name:string):Animal3 } function createClass(clazz:WithClassName,name:string){ return new clazz(name) } let a3 = createClass(Animal3,"别抖腿"); console.log(a3) class和interface的区别 class 类声明并实现方法 in...