[英]Possible to have incompatible aliases in FlowType?
I'm thinking about something like Haskell, where it's a compile-time error to implicitly transfer between different types. 我正在考虑像Haskell这样的东西,它是在不同类型之间隐式传输的编译时错误。
I'd like to be able to do something like: 我希望能够做到这样的事情:
type Username = string;
type Password = string;
function login(username: Username, password: Password): void {
// do some stuff
}
const username: Username = getUsername();
const password: Password = getPassword();
login(password, username); // ideally, should error
Trying this seems to work just fine. 尝试这似乎工作得很好。 I'm wondering if maybe I need something besides a type alias.
我想知道我是否需要除了类型别名之外的东西。 I think it's possible if I wrap it in an object, but I don't know.
我认为如果我将它包裹在一个物体中是可能的,但我不知道。
Is such a thing possible? 这样的事情可能吗?
You can emulate this using classes: 您可以使用类来模拟它:
declare class Password {}
function passwordFromString(str: string): Password {
return (str: any);
}
function passwordToString(pass: Password): string {
return (pass: any);
}
function checkPassword(pass: Password): boolean {
if (passwordToString(pass) === 'foo') {
return true;
}
return false;
}
"Opaque types" are what this is called in Hack. “不透明类型”是Hack中所称的。 Some discussion about implementing them in Flow here: https://github.com/facebook/flow/issues/1056#issuecomment-154876614
关于在Flow中实现它们的一些讨论: https : //github.com/facebook/flow/issues/1056#issuecomment-154876614
Opaque types have been officially implemented in flow. 不透明类型已在流程中正式实施。 Check out the docs here: https://flow.org/en/docs/types/opaque-types/
在这里查看文档: https : //flow.org/en/docs/types/opaque-types/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.