#How to assign new value to an interface

12 messages · Page 1 of 1 (latest)

haughty sable
#

I'm trying to do this:

interface foo {bar: string}

const a: foo & {bar: number} = {bar: 1}

But it tells me the value is not assignable to type never. How can I override a value in an interface?
Thanks

feral sundial
#

you can't

#

you can use Omit to get a new type without the given key

brave pendantBOT
#
interface Foo { bar: string; }
type FooWithNumber = Omit<Foo, 'bar'> & { bar: number; };
//   ^? - type FooWithNumber = Omit<Foo, "bar"> & {
//       bar: number;
//   }
haughty sable
feral sundial
#

it's invalid semantically, not syntactically

#

& is an analog for set intersection, which is commutative

#

"override" is not commutative

#

{ bar: string } & { bar: number } -> { bar: string & number } and you can't have something that's both a string and a number (for primitives) so you get never out of that

#

never is a type that has no possible value, it's an analog to the empty set

#

sidenote; since 'bar' is the only property in Foo, Omit<Foo, 'bar'> is just {}

haughty sable
#

OK thanks