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[]
}
字符串
1条答案
按热度按时间lmyy7pcs1#
使用类型Assert,你实际上是“强迫”数据被认为是某种类型,只要这两种类型以某种方式重叠,TypeScript就允许你这样做。
有时候TypeScript也会提醒你(当数据和类型完全不重叠时)声明“你确定你在做什么”,将数据声明为未知,然后声明为想要的类型,就像在这种情况下:
字符串