typescript 为什么在使用类型Assert时不检查缺少的属性?

7y4bm7vi  于 6个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(85)

TSPlayground
为什么当我使用as和type时,所需的对象键不再被检查?例如,我有Person类型,我需要有name和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[]
}

字符串

lmyy7pcs

lmyy7pcs1#

使用类型Assert,你实际上是“强迫”数据被认为是某种类型,只要这两种类型以某种方式重叠,TypeScript就允许你这样做。
有时候TypeScript也会提醒你(当数据和类型完全不重叠时)声明“你确定你在做什么”,将数据声明为未知,然后声明为想要的类型,就像在这种情况下:

// 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
}

字符串

相关问题