TSシリーズのタイプ
ここにディレクトリのタイトルを書きます
序文
今日はtypeofに関する知識をまとめてみます。
Typeof は、JS で変数の型を決定するためによく使用されるキーワードでもあります。では、Ts での役割は何でしょうか? 見てみましょう。
復習: JS での typeof の使用法
1. typeof の戻り値の型は何ですか?
- "未定義"
typeof undefined
- "物体"
typeof null
或者其他任意对象
null の返される型が object である理由については、次の記事を参照してください: typeof null is 'object'
- 「ブール値」
typeof true
- "番号"
typeof 1
- 「ビギント」
typeof BigInt(1)
- "弦"
typeof ""
- "シンボル"
typeof Symbol(1)
- "関数"
typeof function a () {
}
Ts の typeof 演算子は型判定ツールとして使用されます。
typeofとは何ですか?
typeof
指定された式の型を取得するために使用される TypeScript の演算子です。式型の文字列を返します。
簡単な例:
const num = 1;
const str = "Hello";
console.log(typeof num); // 输出 "number"
console.log(typeof str); // 输出 "string"
この例では、typeof num
「number」が返され、typeof str
「string」が返されますが、これは明らかに js と変わりません。
タイプガードと条件付きタイプ
typeof
演算子の本当の威力は、条件型と組み合わせて使用することにあります。これを条件付きタイプと組み合わせることでtypeof
、実行時にさまざまなタイプのコードに対して条件付き分岐を実行できます。
例: たとえば
、受信した数値または文字列型データを 1 ずつインクリメントして返す関数を実装したいとします。
function test (num: number | string): number | string {
return num++
}
//这时候ts报错,提示:An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.
//意思是:算术操作数的类型必须是“any”、“number”、“bigint”或枚举类型
このとき typeof が役に立ちます。変更は次のようになります。
function test (num: number | string): number | string {
if (typeof num === 'number') {
return ++num;
} else {
return +num + 1;
}
}
複合型
typeof
複合型を判定する場合、使い方はjsの「オブジェクト」「関数」「シンボル」などと同じです。
1. たとえば、オブジェクトがあるとします
。オブジェクトが深くネストされているか、オブジェクトに多くの属性がある場合は、tyoeof を直接使用して属性内のすべての型を取得できます。このオブジェクトの。
const appconfig = {
id: '1',
text: 'app',
appName: 'app',
appImg: 'https://app',
appType: 'app',
positionNum: 1,
url: 'https://app'
}
type appType = typeof appconfig
type appType = {
id: string;
text: string;
appName: string;
appImg: string;
appType: string;
positionNum: number;
url: string;
}
const appconfigtest: appType = {
}
//所以你就可以直接用appType来约束新定义对象appconfigtest
2. オブジェクト内の単一の属性のタイプを取得することもできます
type appType = typeof appconfig.appImg
//type appType = string
3. 関数を通じてクラスのインスタンスを作成して取得したい場合、typeof を通じてクラス コンストラクターの型を取得できます。
class APP {
name: string;
img: string;
constructor (name: string, img: string) {
this.name = name;
this.img = img;
}
}
//(parameter) CP: new (name: string, img: string) => APP
function createApp(CP: typeof APP, name: string, img: string) {
return new CP(name, img);
}
要約する
この時点で、ts での typeof の一般的な使用法については基本的に理解しましたが、その他の使用法については、学習のためにまだ調査して共有する必要があります。