norr
norr

Reputation: 2167

Why missing properties are not checked while using type assertion?

TS playground

Why when I use as with type then required object keys are not checked anymore? For example I have Person type where I need to have name and age.

type Person = {
    name: string,
    age: number,
}

const demo: Person = { // OK - missing 'age' property error
    name: 'test',
} 

const demo2 = { // no missing 'age' property error?
    name: 'test',
} as Person

const demo3 = {  // no missing 'age' property error?
    people: [{
        name: 'test',
    }] as Person[]
}

Upvotes: 0

Views: 562

Answers (1)

InsalataCondita
InsalataCondita

Reputation: 351

With type assertion you are actually "forcing" the data to be considered as some type so, as long as the two types overlap in some way TypeScript allows you to do this.

Sometimes TypeScript also reminds you (when the data and the type does not overlap at all) to declare that "you are sure of what you are doing" declaring the data as unknown and then as the wanted type, like in this case:


// No overlap at all
const demo3 = { 
    people: [{
        foo: 'test',
    }] as Person[]
}

// telling TypeScript "yes, I'm sure of what I am doing"
const demo4 = { 
    people: [{
        foo: 'test',
    }] as unknown as Person[] // also "as any as Person[]" will work
}


Upvotes: 2

Related Questions