Common function allows arbitrary keys

Why is the code compiling successfully? Since barit is not part MyState, I expect it to generate a compiler error.

type MyState = { foo: number; };
type Reducer<T> = (state: T) => T;

const wtf: Reducer<MyState> = (state) => {
  return { foo: 123, bar: 123 }; // `bar` isn't part of MyState
};
+4
source share
2 answers

Type Compatibility in TypeScript is based on structural subtyping. Structural typing is a way of binding types based solely on their members. This contrasts with typical typing.

Type compatibility

, y x, x, y. y , , . , . : y location, . ( ).

, { foo: 123, bar: 123 } foo, , bar .

: . ? ?

+4

crashmstr , , , .

.

:

var x: MyState = { foo: 10, bar: 20 };

:

  • , MyState ( )
  • , :
    • ?
      • {foo: 10, bar: 20}
    • MyState?
      • foo?
      • ?
        • (10number)
      • ?

. , . ,

// Error
var x: MyState = { foo: 10, bar: 20 };

// OK
var x1 = { foo: 10, bar: 20 };
var x2: MyState = x1;

, x1.

- , . , , .

+5

Source: https://habr.com/ru/post/1684404/


All Articles