我有一个通用的Id<T: HasId>
结构上始终只是 string
的类型无论传入的类型参数如何 T
。我想要Id<T>
具有不同类型的类型传递为 T
表现得像不同类型。
例如,我想要片段 const i :Id<Car> = p.id
在以下代码中导致 Flow 错误:
declare interface HasId {
id: string,
};
type Id<T: HasId> = string;
type Person = {
id: Id<Person>,
name: string,
};
type Car = {
id: Id<Car>,
make: string,
model: string,
};
const p :Person = { id: '1234', name: 'me' }
const c :Car = p; // Causes a Flow error, good!
const c :Id<Car> = p.id; // I want this to cause a Flow error,
// but currently it doesn't.
此外,如果这可以继续与联合类型很好地配合,那就太好了:
type Vehicle =
| Car
| Motorcycle
;
const t :Car = { id: '5678', make: 'Toyota', model: 'Prius' };
const v :Id<Vehicle> = c.id; // Currently does not cause Flow
// error; I want to keep it that way.
最佳答案
听起来你想要的是不透明类型,而 Flow 还没有。如果您有类型别名 type MyString = string
,则可以互换使用 string
和 MyString
。但是,如果您有不透明类型别名 opaquetype MyNumber = number
,则不能互换使用 number
和 MyNumber
。
不透明类型有更长的解释 on this GitHub issue .
关于javascript - Flowtype:通用 Id<T> 类型,与传入的类型参数具有类似的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679567/