【问题标题】:Implementing a Base64 type in Flow在 Flow 中实现 Base64 类型
【发布时间】:2017-03-17 17:22:46
【问题描述】:

我有一个返回 base64 编码值的函数,类似于:

token = (unencoded:string):string => {
  return Buffer.from(unencoded).toString('base64')
}

我想返回一个表明内容是 base64 编码的类型。我可以通过将字符串分配给新类型来伪造它:

type Base64 = string
token = (unencoded:string):Base64 => {
  return Buffer.from(unencoded).toString('base64')
}

这样做的缺点是在类型比较中 Base64 等于字符串,所以它只能作为糖。我想知道是否有一种方法可以更深入地断言关于字符串本身的事情?

【问题讨论】:

  • 我打赌在任何静态分析工具中都不可能。
  • 您可以制作某种包装器,例如将其包装在具有 valueOftoString 设置为返回值的类中,但我不知道还有其他简单的方法.

标签: ecmascript-6 flowtype


【解决方案1】:

你可以假装它:

type Encoding<A> = A;
type Base64 = string & Encoding<'base64'>;
const toBase64 = (v: string): Base64 => 
  ((Buffer.from(v).toString('base64'): any): Base64);

function test(aB64String: Base64): void {
  console.log(aB64String);
}

let v = 'blah';

test(v);           
// ^ Cannot call `test` with `v` bound to `aB64String` because string [1] is incompatible with string literal `base64` [2]

test(toBase64(v));
// ^ OK √

这样每次使用Base64类型时,你都需要通过toBase64函数传递你的字符串值来获取实际的Base64类型值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多