[Typescript] Tuple types
6946 ワード
🎯 Goals tupleタイプの定義と特徴を理解します. tupleタイプをいつ使うか知ることができます. 定義#テイギ#
要素数と要素タイプで配列されたアレイ.
jsは異なるタイプの要素に含まれることを知っています.
(実際、jsでは配列はインデックス番号をキーとするハッシュマッピングにすぎない)
When to use?定義の要素数とタイプ定義の「tuple(レコード)」を使用する場合、 API定義では、属性名を柔軟に定義する必要はありません.
ex) React's 設計図と同時に任意に属性を命名する場合、 固定された属性名とオブジェクト単位を使用する必要がある場合、次のコードは構造化されたモードです.
Object Version
Tuple version
また、destructuringの場合、プロパティの名前は元のオブジェクトのpropertyと一致する必要はありません.また、spread、optional typeを設定することもできます.
上記の例では、z座標がなくても大丈夫です.
また,
Promise.all Typescript document powerful tuple types - git connected
要素数と要素タイプで配列されたアレイ.
jsは異なるタイプの要素に含まれることを知っています.
(実際、jsでは配列はインデックス番号をキーとするハッシュマッピングにすぎない)
When to use?
ex) React's
useState
const [error, setError] = useState(null);
Object Version
interface Point {
x: number;
y: number;
}
const point1 : Point = {x: 5, y: 3};
// { x: 5, y: 3 }
console.dir(point1);
これでどうですか.Tuple version
type TuplePoint = [number, number, number?];
const [x, y, z] : TuplePoint = [10, 12];
// x: 10, y: 12, z: undefined
console.log(`x: ${x}, y: ${y}, z: ${z}`);
違いは、point
は客体であり、resultType
は配列である.また、destructuringの場合、プロパティの名前は元のオブジェクトのpropertyと一致する必要はありません.また、spread、optional typeを設定することもできます.
上記の例では、z座標がなくても大丈夫です.
また,
Promise.all
のすべての結果値を一括して取り戻す場合にも用いられる.Promise.all
(async ()=>{
const [name, age, date] = await Promise.all([
Promise.resolve('falcon'),
Promise.resolve(33),
Promise.resolve(new Date())
]);
// falcon 33 2021-09-09T07:34:24.060Z
console.log(name, age, date)
})();
🔗 ReferenceReference
この問題について([Typescript] Tuple types), 我々は、より多くの情報をここで見つけました https://velog.io/@milkcoke/Typescript-Tuple-typesテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol