简体   繁体   English

可能在FlowType中具有不兼容的别名?

[英]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.

相关问题 Flowtype - 字符串与字符串枚举不兼容 - Flowtype - string incompatible with string enum 流类型:字符串类型与字符串枚举不兼容 - Flowtype: string type is incompatible with string enum 流类型错误。 对象类型与字符串不兼容 - Flowtype error. Object type is incompatible with string flowtype 无法返回 object 文字,因为 object 类型不兼容 - flowtype cannot return object literal because object type is incompatible 是否可以一起使用flowtype和async await转换? - Is it possible to work with flowtype and async await transforms together? 打字稿:是否可以引用类型别名 - Typescript: Is it possible to reference type aliases flowtype bind导致错误`Convariant属性与在赋值属性时的逆变使用不兼容 - flowtype bind cause error `Convariant property incompatible with contravariant use in assignment of property` 如何使用flowtype在组件的反应上下文中定义prop? - how is it possible to use flowtype to define a prop in react context of a component? ImmutableJS / FlowType:是否可以类型检查List.toJS()返回的数组 - ImmutableJS/FlowType: Is it possible to typeCheck an array returned by a List.toJS() FlowType:为什么函数类型具有命名参数? 他们的目的是什么? - FlowType : why function types have named parameters ? What is their purpose?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM