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, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15866038.html
未经授权禁止转载,违者必究!

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号