#Why can't I create an object literal with extra keys that satisfies X

11 messages · Page 1 of 1 (latest)

winter muskBOT
#
type Foo = {
    a: number,
    b: string
}

const foo = {
    a: 1,
    b: 'a',
    c: true
//  ^
// Object literal may only specify known properties, and 'c' does not exist in type 'Foo'.
} satisfies Foo
frail quartz
#

Am I being totally brain dead? Isn't this fine?

#

I guess it is just overzealous EPC

sage dawn
#

it's valid to the type system, but it's a possible/probable mistake, so it's checked for the benefit of the dev

winter muskBOT
#
type X = {
  some?: boolean
  optional?: boolean
  properties?: boolean
}

const x = {
  some: true,
  optoinal: false // typo!
//^^^^^^^^
// Object literal may only specify known properties, but 'optoinal' does not exist in type 'X'. Did you mean to write 'optional'?
} satisfies X
frail quartz
#

Yeah I get that. Just seems like a pretty legit use

#

Where I want to create an object, but just make sure it complies with a constraint

winter muskBOT
#
type Foo = {
    a: number,
    b: string
}

const foo = {
    a: 1,
    b: 'a',
    c: true
}
const _: Foo = foo
frail quartz
#

So this is the way?

azure summit
#

@frail quartz You can do

const foo = {
    a: 1,
    b: 'a',
    c: true
} 
foo satisfies Foo;
frail quartz
#

ah? That's cool