为什么 Object.entries return 是联合类型?
Why does Object.entries return a union type?
我正在使用以下代码,打字稿 4.7.3,不明白为什么 amount
的类型不是 PositiveNumber
。
export type PositiveNumber = number & { __type: 'PositiveNumber' }
export type PointsByAbbrev = Record<string, PositiveNumber> & { __type: 'PointsByAbbrev' }
export const isPointsByAbbrev = (value: Record<string, number> | null | undefined): value is PointsByAbbrev => hasValue(value) && Object.values(value).every(x => x >= 0)
class Foo {
data!: PointsByAbbrev
generate(input: Record<string, number>) {
if (isPointsByAbbrev(input))
this.data = input
}
someMethod(): void {
Object.entries(this.data).forEach(([abbrev, amount]) => {
})
}
}
根据编译器,amount
的类型是PositiveNumber | "PointsByAbbrev"
我正在通过类似 generate
方法的过程分配 data
显示我通过类型保护传递输入的位置,然后在为真时分配。
看起来您正在尝试使用 __type
字段做一些新类型模式,但这并没有使该字段变得不那么真实。就 Typescript 而言,__type
是对象上的有效插槽,其类型为 'PointsByAbbrev'
。 this.data
的类型是
Record<string, PositiveNumber> & { __type: 'PointsByAbbrev' }
Record<string, PositiveNumber>
的字段类型为PositiveNumber
,{ __type: 'PointsByAbbrev' }
的字段类型为'PointsByAbbrev'
,所以整个交集类型的字段类型为PositiveNumber | 'PointsByAbbrev'
我正在使用以下代码,打字稿 4.7.3,不明白为什么 amount
的类型不是 PositiveNumber
。
export type PositiveNumber = number & { __type: 'PositiveNumber' }
export type PointsByAbbrev = Record<string, PositiveNumber> & { __type: 'PointsByAbbrev' }
export const isPointsByAbbrev = (value: Record<string, number> | null | undefined): value is PointsByAbbrev => hasValue(value) && Object.values(value).every(x => x >= 0)
class Foo {
data!: PointsByAbbrev
generate(input: Record<string, number>) {
if (isPointsByAbbrev(input))
this.data = input
}
someMethod(): void {
Object.entries(this.data).forEach(([abbrev, amount]) => {
})
}
}
根据编译器,amount
的类型是PositiveNumber | "PointsByAbbrev"
我正在通过类似 generate
方法的过程分配 data
显示我通过类型保护传递输入的位置,然后在为真时分配。
看起来您正在尝试使用 __type
字段做一些新类型模式,但这并没有使该字段变得不那么真实。就 Typescript 而言,__type
是对象上的有效插槽,其类型为 'PointsByAbbrev'
。 this.data
的类型是
Record<string, PositiveNumber> & { __type: 'PointsByAbbrev' }
Record<string, PositiveNumber>
的字段类型为PositiveNumber
,{ __type: 'PointsByAbbrev' }
的字段类型为'PointsByAbbrev'
,所以整个交集类型的字段类型为PositiveNumber | 'PointsByAbbrev'