xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript Interface All In One

TypeScript Interface All In One


// interface 接口

interface Person {
  name: string,
  // (property) Person.name: string
  age: number,
  // (property) Person.age: number
  hobbies?: string[],
  // (property) Person.hobbies?: string[] | undefined
}

function User(person: Person): void {
  const { name, age, hobbies } = person;
  console.log('name, age, hobbies =', name, age, hobbies);
}

// const user = new User({
//   name: 'xgqfrms',
//   age: 23,
//   hobbies: ['fishing', 'reading'],
// });

// 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)

// const user = User({
//   name: 'xgqfrms',
//   age: 23,
//   // hobbies: ['fishing', 'reading'],
// });

/*
Argument of type '{ name: string; age: number; }' is not assignable to parameter of type 'Person'.
  Property 'hobbies' is missing in type '{ name: string; age: number; }' but required in type 'Person'.ts(2345)
*/

const user = User({
  name: 'xgqfrms',
  age: 23,
  // hobbies: ['fishing', 'reading'],
});

// function User(person: Person): void {
//   this.person = person;
//   // this.name = name;
//   // this.age = age;
//   // this.hobbies = hobbies;
//   log() {
//     const { name, age, hobbies } = person;
//     console.log('name, age, hobbies =', name, age, hobbies);
//   }
// }





TypeScript 多接口继承

interface IParent1 { 
  v1:number;
}
 
interface IParent2 { 
  v2:number; 
}

// 多接口继承语法格式:继承的各个接口使用逗号 , 分隔。
interface Child extends IParent1, IParent2 {
  // 
}

const Iobj:Child = {
  v1: 1,
  v2: 2,
} 

console.log("value 1: " + Iobj.v1 + " value 2: "+ Iobj.v2)

refs

https://www.typescriptlang.org/docs/handbook/2/objects.html#interfaces-vs-intersections

https://www.typescriptlang.org/docs/handbook/interfaces.html



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(29)  评论(4编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-02-06 Google 灭霸 彩蛋
2020-02-06 POST 非幂等 All In One
点击右上角即可分享
微信分享提示