跳至主要內容

版本 0.21.0

昨天我們部署了 Flow v0.21.0!一如往常,我們在 變更日誌 中列出了最有趣的變更。不過,由於我正在飛機上且無法入睡,所以我認為深入探討幾個變更可能會很有趣!希望這篇部落格文章會很有趣且易於閱讀!

JSX 內建元素

如果您正在撰寫 JSX,它可能是您自己的 React 元件和一些內建元素的組合。例如,您可能會撰寫

render() {
return <div><FluffyBunny name="Fifi" /></div>;
}

在此範例中,FluffyBunny 是您撰寫的 React 元件,而 div 是 JSX 內建元素。React 和 Flow 會假設小寫的 JSX 元素為內建元素。在 Flow v0.21.0 之前,Flow 會忽略內建元素並將其類型設為 any。這表示 Flow 讓您可以在 JSX 內建元素上設定任何屬性。Flow v0.21.0 預設會執行與 v0.20.0 相同的動作,不過現在您也可以設定 Flow 以正確輸入您的 JSX 內建元素!

如何使用 JSX 內建元素的範例

.flowconfig

[libs]
myLib.js

myLib.js

// JSXHelper is a type alias to make this example more concise.
// There's nothing special or magic here.
// JSXHelper<{name: string}> is a React component
// with the single string property "name", which has a default
type JSXHelper<T> = Class<ReactComponent<T,T,mixed>>;

// $JSXIntrinsics is special and magic.
// This declares the types for `div` and `span`
type $JSXIntrinsics = {
div: JSXHelper<{id: string}>,
span: JSXHelper<{id: string, class: string}>,
};

myCode.js

<div id="asdf" />; // No error
<div id={42} />; // Error: `id` prop is a string, not a number!

這裡發生了什麼事?

新的魔法是這個 $JSXIntrinsics 類型別名。當 Flow 看見 <foo /> 時,它會查看 $JSXIntrinsics 是否存在,如果存在,它會取得 $JSXIntrinsics['foo'] 的類型。它會使用這個類型來找出哪些屬性可用且需要設定。

我們沒有將內部函式硬編碼到 Flow 中,因為可用的內部函式會依據您的環境而定。例如,React Native 會有不同於 React for the web 的內部函式。

更聰明的字串精鍊

我們讓 Flow 變得更聰明的主要方法之一,是教導它辨識更多 JavaScript 程式設計師精鍊類型的途徑。以下是精鍊可為空值的常見方法範例

class Person {
name: ?string;
...
getName(): string {
// Before the if, this.name could be null, undefined, or a string
if (this.name != null) {
// But now the programmer has refined this.name to definitely be a string
return this.name;
}
// And now we know that this.name is null or undefined.
return 'You know who';
}
}

新的字串精鍊

在 v0.21.0 中,我們新增的精鍊之一是能夠透過將類型與字串相比較來精鍊類型。

這對於將字串文字的聯集精鍊為字串文字很有用

function test(x: 'foo' | 'bar'): 'foo' {
if (x === 'foo') {
// Now Flow understands that x has the type 'foo'
return x;
} else {
return 'foo';
}
}

也可以縮小字串的值

function test(x: string): 'foo' {
if (x === 'foo') {
// Now Flow knows x has the type 'foo'
return x;
} else {
return 'foo';
}
}

這是 Flow 目前可以辨識和遵循的眾多精鍊之一,而且我們會持續新增更多!敬請期待!