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);
//   }
// }





refs

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

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


Flag Counter

?xgqfrms 2012-2020

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

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!