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!