4 ms·
Not really, and correct me if I'm wrong but afaik TS doesn't actually do row polymorphism so much as structural subtyping - although the difference between the
by inbx0 5y ago
Not really, and correct me if I'm wrong but afaik TS doesn't actually do row polymorphism so much as structural subtyping - although the difference between the two is pretty small and you can get pretty close to row polymorphism with structural subtyping + generics.
But even if these were the same thing and we want to be a bit pendantic since this is HN after all, structural type systems often support some kind of subtyping or row polymorphism, but it's not a strict requirement for a type system to be "structural". You could have a structural type system that doesn't allow
{ a: int, b: int }
to be used where
{ a: int }
is expected. How practical such a type system would be... I don't know. Flow type checker for JavaScript makes a distinction between "exact" types, i.e. object must have exactly the properties listed and no more, and "inexact" types where such subtyping is allowed.
- seanwilson 5y ago> How practical such a type system would be... I don't know. Flow type checker for JavaScript makes a distinction between "exact" types, i.e. object must have exactly the properties listed and no more, and "inexact" types where such subtyping is allowed. TypeScript doesn't have this check (https://github.com/Microsoft/TypeScript/issues/12936 https://github.com/Microsoft/TypeScript/issues/12936) and I've found it can be really error prone when you're wanting to return a copy of an object with some fields updated. Spot the bug in this example: https://www.typescriptlang.org/play?#code/C4TwDgpgBAKlC8UDeUCWATAXFAzsATqgHYDmANFAMYD2ANrRJcKtUdnoaQNoC6AvgG4AsAChRAMwCuRJiyJQAhunQAKYJhgUAbgtqSI7AsRIBKKBuSio1qqzxRJYdAuDRESGvUbNWAJmxcAHTBwIGeDLKs2rr6-MIiNlD4EMCS+PJIwYHAFFmOzq6ConyiojREOHQQgbTUJCpKqkgYmABEAB6tFOHecphcrQpdUK0ARq38FK2UrSYm8UA https://www.typescriptlang.org/play?#code/C4TwDgpgBAKlC8UDeU...
- mixedCase 5y agoFWIW, you can achieve row polymorphism in TypeScript, although it's not super intuitive. function rowPolymorphic<R extends { a: number }>(record: R): R & { a: string } { return { ...record, a: record.a.toString(), } } const rec = rowPolymorphic({ a: 123, b: "string", }) console.log(rec.b)