kakts-log

programming について調べたことを整理していきます

TypeScript: A difference of type-checking behavior for passing Object directly and indirectly.

TypeScript interface

I'm a newbie of TypeScript. I was confused by an error for the type-checking of interface.

This is just a memorandum for understanding the mechanism of TypeScript

I created the SquareConfig interface same as the TypeScript official document. Interfaces · TypeScript

In SquareConfig interface. color and width are both optional. and according to the document, if passing an Object having more properties than the compiler expected, it doesn't emit an error.

Notice that our object actually has more properties than this, but the compiler only checks that at least the ones required are present and match the types required. There are some cases where TypeScript isn’t as lenient, which we’ll cover in a bit.

But I change the code a little, it emits an error

Good

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
  return {
    color: 'tset',
    area: 1
  }
}
const test = {color: 'test', width: 100, test: 'test'}
createSquare(test)

If I pass the Object argument to createSquare function indirectly, it's completely through the build process. In this case, the "test" parameter is But, see below, if I pass the Object directly, it occurs an error.

Bad

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
  return {
    color: 'tset',
    area: 1
  }
}
// const test = {color: 'test', width: 100, test: 'test'}
// passing the 
createSquare({color: 'test', width: 100, test: 'test'})

when build it, TypeScript emits an error.

[01:13:06] Using gulpfile ~/Documents/code/nodejs-sandbox/ts-app/gulpfile.js
[01:13:06] Starting 'default'...
src/subfolder/squareConfig.ts(13,42): error TS2345: Argument of type '{ color: string; width: number; test: string; }' is not assignable to parameter of type 'SquareConfig'.
  Object literal may only specify known properties, and 'test' does not exist in type 'SquareConfig'.
TypeScript: 1 semantic error

Why does this error occur?