如何在TypeScript中创建条件类型

如何在TypeScript中创建条件类型

在本文中,我们将看到如何在TypeScript中创建条件类型。

决策使函数对不同类型的输入非常有用。条件类型就像其名字所示,根据条件定义值的类型。现在,条件类型似乎类似于条件语句,尽管它的使用方式与条件语句相同,根据某些条件选择代码流程,而条件类型用于为值选择不同的类型。

语法: 我们可以使用TypeScript中的三元运算符和extends来创建条件类型。

Type1 extends Type2 ? 对于某个值 : 对于另一个值;
HTML

在这里,extends函数作为比较函数工作,它检查Type1是否具有Type2的属性,如果是,则跳转到true分支,否则跳转到false分支。

现在让我们通过以下示例来理解。

示例1: 在这个例子中,我们将创建条件类型,它接受值并检查它是否具有number属性,如果它具有number属性,条件类型将将类型分配给条件类型的调用者,否则将类型分配为never。

// TypeScript的分配特性
type return_dis<D>= D extends number ? D : never;
type show = number;
// number的条件类型
type new_number = return_dis<show>;
let n1 : new_number = 88;
console.log(n1);
console.log(typeof n1)
HTML

输出:

88
number
HTML

示例2: 现在,我们将通过缩小输入数据的功能来创建条件类型。在这种类型的创建条件类型中,我们将筛选出包含某些值的特定输入类型。这里,我们使用扩展函数和一组值来缩小条件类型。首先,我们将创建条件类型来检查属性是否具有数字、字符串或布尔类型,如果是,则如果它具有

type Conditional<G> = G extends {typeof : number|string|Boolean} ? G :"This is an error";
let n = 55;
type nu = Conditional<typeof n>;
let s = "hello world";
type Str = Conditional<s>;
let b = Boolean;
type Boo = Conditional<typeof b>;
let k = null;
type SecondCond = Conditional<typeof k>;
let l1: nu = 88;
console.log(l1);
let l2: Str = "Hello Geeks";
console.log(l2);
let l3: Boo = true;
console.log(l3);
let l: SecondCond = "This is an error";
console.log(l);
HTML

输出:

88
Hello Geeks
true
This is an error
HTML

示例3: 在这个例子中,首先,我们将在一个条件类型中为数字和字符串分别创建条件类型。然后,我们将使用相同的条件类型同时用于字符串和数字。

// TypeScript的分配特性
type return_dis<D>= D extends number|string ? D : never;
type show = number|"Geek";
// 数字的条件类型
type new_number = return_dis<show>;
let n1 : new_number = 88;
console.log(n1);
// 字符串也使用同一类型
type new_Geek = return_dis<show>;
let G1 : new_Geek = "Hey Geeks";
console.log(G1)
HTML

输出:

88
Hey Geeks
HTML

阅读更多:JavaScript 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册