是否有 Flow 的不完整(部分)声明之类的东西?
Is there something like incomplete (partial) declarations for Flow?
我想逐步添加外部库的声明。是否可以编写仅描述 object/interface 的某些属性的声明,而其余属性从声明中省略,因此未被选中?
例如:可以跟随对象
const a = {foo: 8, bar: 9}
声明只描述了一个 属性?
declare var a: any|{foo: number} // doesn't actually work
预期的行为是,如果在声明中找到 属性,则强制执行该类型。所有未提及属性的类型被认为是 any
.
Typescript 使用额外的属性表达式解决了这个问题:
interface Iface {
foo: number;
[propName: string]: any;
}
type PartialA = {foo:number, [key:string]: any}
const a: PartialA = {foo: 1, bar: 2}
console.log(a.bar)
此选项比以下选项更安全,因为强制执行已知属性的类型:
a.foo = 'a' // causes error
// 6: a.foo = 'a'
// ^ string. This type is incompatible with
// 3: type PartialA = {foo:number, [key:string]: any}
// ^ number
或
type PartialB = {foo:number}&any
const b: PartialB = {foo: 1, bar: 2}
console.log(b.bar)
b.foo = 'a' // Ok in Flow
已使用 Flow v0.34.0 进行测试
来源:@loganfsmyth, @gcanti
我想逐步添加外部库的声明。是否可以编写仅描述 object/interface 的某些属性的声明,而其余属性从声明中省略,因此未被选中?
例如:可以跟随对象
const a = {foo: 8, bar: 9}
声明只描述了一个 属性?
declare var a: any|{foo: number} // doesn't actually work
预期的行为是,如果在声明中找到 属性,则强制执行该类型。所有未提及属性的类型被认为是 any
.
Typescript 使用额外的属性表达式解决了这个问题:
interface Iface {
foo: number;
[propName: string]: any;
}
type PartialA = {foo:number, [key:string]: any}
const a: PartialA = {foo: 1, bar: 2}
console.log(a.bar)
此选项比以下选项更安全,因为强制执行已知属性的类型:
a.foo = 'a' // causes error
// 6: a.foo = 'a'
// ^ string. This type is incompatible with
// 3: type PartialA = {foo:number, [key:string]: any}
// ^ number
或
type PartialB = {foo:number}&any
const b: PartialB = {foo: 1, bar: 2}
console.log(b.bar)
b.foo = 'a' // Ok in Flow
已使用 Flow v0.34.0 进行测试
来源:@loganfsmyth, @gcanti