flowforfrank / webtips

https://webtips.dev
1 stars 0 forks source link

solutions/extending-types-in-typescript #23

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Extending Types in TypeScript The Right Way - Webtips

Learn how you can extend types in TypeScript using the & operator.

https://www.webtips.dev/solutions/extending-types-in-typescript?utterances=eb3cec57322f3f64ab0d5b0d7xQPoWrkqwqS%2BBdYmkk3SqILeF2pWcKqi%2FsGwzxKzLUHdH25uI11T5t5MissC3Ts9qzK1YP0ei%2BdoIoROhoHOQ70uJUjjBeR5pqQppskjaK1y53YWGrNztFkLJk%3D

tilakbasyal commented 1 year ago

You have mentioned that You also have the option to extend types using the extends keyword, not just interfaces,.... I don't think types can be extended using the extends keyword. Only classes and interfaces can be extended by using the extends keyword. Please correct me if my understanding is wrong.

type One = {
  name: string
}

// error
type Two extends One {
  age: number
}

// no error
type Twoo = One & { age: number }

// no error
interface Tow extends One {
  age: number
} 
flowforfrank commented 1 year ago

Hey @tilakbasyal that's correct, only interfaces and classes can use the extends keyword. I meant to point out that you can extends types for interfaces, not just other interfaces. I will reword the sentence to make it more clear. Thanks for bringing this up!