0
interface IConfig1 {
    name: string,
    age: string
}

interface IConfig2 {
    name: string
}

const config1: IConfig1 = {
    name: "123",
    age: "123"
}

var config2: IConfig2 = {
    // Type '{ age: string; name: string; }' is not assignable to type 'IConfig2'.
    // Object literal may only specify known properties, and 'age' does not exist in type 'IConfig2'.(2322)
    age: "123", 
    name: "123"
}

// Why no error 
var config3: IConfig2 = config1

playground

Defining the config2 object throws an error because the age does not exist in type IConfig2. But what confuses me is why config3 don't throw the error 'age' does not exist in type 'IConfig2'.

How to fix it? make config3 throw the error.

3
  • As the error says, Object literal only looks for excess properties Commented May 10, 2021 at 8:02
  • Read this post: stackoverflow.com/questions/67454660/… There is a similar question i answered yesterday, it is related to type compatibility feature in typescript where IConfig1 fulfilled all requirement in and compatible with IConfig2 which has { name: string } so config3 has no error Commented May 10, 2021 at 8:08
  • @MicFung Thanks for your explanation, how to fix it? Commented May 10, 2021 at 8:31

1 Answer 1

1

It is called excess-property-checks

Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments.

In your second example:

var config3: IConfig2 = config1

you are using object reference instead of literal, that's why excess property checking is disabled

UPDATE

// Type for function arguments
type Strict<A, B> = keyof A extends keyof B ? keyof B extends keyof A ? A : never : never

const strict = <T, U extends Strict<T, IConfig2>>(arg: T, ...validation: T extends U ? [] : [never]) => arg
const x = strict(config2) // ok
const y = strict(config1) // expected error

Please keep in mind, Strict type just checks first level of properties. If your config object has nested properties it will not work

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

2 Comments

Thanks, how to make config3 throw the error?
@YuMiao it is doable but it requires function overhead. Are you ok with that?

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.