2

I've got an anonymous object with a TypeScript typed property. Something like this:

type Foo = {
  exists: true;
  bar: string;
};

doSomething({
  foo: {
    exists: true,
    bar: 'baz',
  } as Foo,
});

I'd like to type protect the foo property so if type Foo ever changes in the future (e.g. gets a new property), then the TypeScript compiler will warn me. While these cause compiler errors:

doSomething({
  foo: {
    exists: 'string', // Incorrect type
    bar: 'baz',
  } as Foo
});

doSomething({
  foo: {
    say: 'hello', // Not enough overlap with Foo
    bar: 'baz',
  } as Foo
});

This doesn't cause a type error, even though exists is missing:

doSomething({
  foo: {
    bar: 'baz',
  } as Foo
});

Likewise, this also doesn't cause a type error:

doSomething({
  foo: <Foo>{
    bar: 'baz',
  },
});

The only way I can force a type error when a property of Foo is missing is this:

const foo: {foo: Foo} = {
  foo: {
    bar: 'baz',
  },
};

doSomething(foo);

...but that requires me to unnecessarily create a local variable simply for the purpose of type safety. Is there a way to type protect the property of an anonymous object?

Note: doSomething()'s parameter accepts any and doesn't enforce any type requirements, otherwise I could rely on doSomething enforcing the type.

1 Answer 1

2

TypeScript 4.9 will introduce the satisfies operator.

doSomething({
  foo: {
    bar: 'baz',
  } satisfies Foo,
});

Until then, you may use another function to validate foo at compile time.

const validFoo = (foo: Foo) => foo

doSomething({
  foo: validFoo({
    bar: 'baz',
  }),
});

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.