Flow Typeof类型(Typeof Types)

Typeof类型(Typeof Types)

获取值的内部类型
JavaScript有一个typeof运算符,它返回描述值的字符串。

typeof 1 === 'number'
typeof true === 'boolean'
typeof 'three' === 'string'

然而,这个字符串仅仅描述了类型是不够的。

typeof { foo: true } === 'object'
typeof { bar: true } === 'object'
typeof [true, false] === 'object'

Flow中提供了相似的typeof运算符,但是功能更强大。

typeof类型语法

typeof运算符返回给定值的Flow类型以用作类型。

// @flow
let num1 = 42;
let num2: typeof num1 = 3.14;     // Works!
// $ExpectError
let num3: typeof num1 = 'world';  // Error!

let bool1 = true;
let bool2: typeof bool1 = false;  // Works!
// $ExpectError
let bool3: typeof bool1 = 42;     // Error!

let str1 = 'hello';
let str2: typeof str1 = 'world'; // Works!
// $ExpectError
let str3: typeof str1 = false;   // Error!

你可以对任何值使用typeof

// @flow
let obj1 = { foo: 1, bar: true, baz: 'three' };
let obj2: typeof obj1 = { foo: 42, bar: false, baz: 'hello' };

let arr1 = [1, 2, 3];
let arr2: typeof arr1 = [3, 2, 1];

typeof继承推导行为

Flow会对你的代码进行各种类型的推导。当你使用typeof的时候,你将把Flow的推理结果作为一个类型来声明。虽然这可能非常有用,但也会导致一些意想不到的结果。

例如,在Flow中使用字面量值时,它们的推导类型就是它所属的基本类型。因此,数字42具有推导的数字类型。你可以看到这个当你使用typeof

// @flow
let num1 = 42;
let num2: typeof num1 = 3.14;    // Works!

let bool1 = true;
let bool2: typeof bool1 = false; // Works!

let str1 = 'hello';
let str2: typeof str1 = 'world'; // Works!

但是,这只会发生在推导的类型。如果你指定了字面量类型,它将在typeof中使用。

// @flow
var num1: 42 = 42;
// $ExpectError
var num2: typeof num1 = 3.14;    // Error!

let bool1: true = true;
// $ExpectError
let bool2: typeof bool1 = false; // Error!

let str1: 'hello' = 'hello';
// $ExpectError
let str2: typeof str1 = 'world'; // Error!

typeof继承其它类型的行为

Flow中有许多不同的类型,其中一些类型的行为与其他类型不同。这些差异对于这种特定的类型是有意义的,但对其他类型则不是。

当你使用typeof时,你将传入另一个类型的所有行为。所以typeof的表现不定一是固定的。

例如,如果你在一个类中使用typeof,你需要记住,类是名义上的类型,而不是结构类型。因此,具有相同形状的两个类不被认为是等同的。

// @flow
class MyClass {
  method(val: number) { /* ... */ }
}

class YourClass {
  method(val: number) { /* ... */ }
}

// $ExpectError
let test1: typeof MyClass = YourClass; // Error!
let test1: typeof MyClass = MyClass;   // Works!
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,221评论 0 13
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 3,925评论 1 10
  • 人生路漫漫,我们每个人都有梦想,也不止一个梦想。在不同的阶段,我们有着不同的梦想。有大梦想也有小梦想,大梦...
    柠檬味的金桔阅读 294评论 0 0
  • 昨晚,刚满四周岁的大宝忽然问我:“妈妈,你是不是当妈妈当够了?” 被这句话愣在当场,当妈妈,不是玩游戏,岂能玩够了...
    方土令阅读 249评论 0 0
  • 突然的文章书写,我不擅长。或许这是我的阅历不够丰富,或许这是我的习惯没有养成,但我想这个软件,或许能够为我提供一...
    岩鲸阅读 357评论 0 1