1

I was testing out functions, when I discovered intresting behevior. For some reason function accepts a "Larger" type, when "Smaller" is required.

  • Why?
  • And how to make it strict?

type Larger = {
  prop1: string,
  prop2: string,
};

type Smaller = {
  prop1: string;
}

const foo = (param: Smaller): Smaller => param;

const larger: Larger = {
  prop1: 'prop1',
  prop2: 'prop2'
};
const result: Smaller = foo(larger);
  • 1
    TypeScript has [structural subtyping](https://www.typescriptlang.org/docs/handbook/type-compatibility.html#starting-out); object types in TypeScript are "open"/"extendible" and not "closed"/"sealed"/"exact". A type like `{prop1: string}` means "this object has a `prop1` property whose value is of type `string`". It does not mean that `prop1` is the *only* property. There are ways to try to simulate exact types with generics, but they can all ultimately be circumvented. You would do well to work with the type system instead of against it, and don't write code that cares about extra properties. – jcalz Feb 11 '22 at 02:19

0 Answers0