在 TypeScript 中检查一个变量是否是一个字符串 | 您所在的位置:网站首页 › ts判断类型中有某个值 › 在 TypeScript 中检查一个变量是否是一个字符串 |
TypeScript 类型
在 TypeScript 中使用 typeof 运算符检查变量是否为字符串
在 TypeScript 中使用 instanceof 运算符检查变量是否为字符串
在 TypeScript 中使用 Object.prototype 检查变量是否为字符串
本文将讨论在 TypeScript 中检查变量是否为字符串。 TypeScript 类型TypeScript 是 JavaScript 语言的超集,类型检查在编译时进行。每当声明变量、函数或参数时,TypeScript 允许我们显式分配类型,这有助于提前识别错误。 // variable declaration and assignment let stringTypeVariable: string = 'Hello world'; let booleanTypeVariable: boolean = true; let numberTypeVariable: number = 10; // function declaration function calculateSum(numOne: number, numTwo: number): number { return numOne + numTwo; } TypeScript 中的 string 类型TypeScript 字符串类型包含一组字符。它是一种原始数据类型,其中一个字符序列包含在单引号或双引号之间。 文本数据可以存储在字符串类型中。有两种方法可以在 TypeScript 中存储字符串: 存储为原始类型 存储为对象实例 将字符串存储为原始类型通常,原始字符串类型包含字符串文字。建议使用原始字符串而不是对象实例。 let stringTypeName: string = 'John Doe'; let stringTypeId: string = "User001"; 将字符串存储为对象实例TypeScript 支持 String 对象实例,它使用附加的辅助方法包装原始字符串类型。String 对象实例将在其原型链中具有 String.prototype。 let stringVal: String = new String('This is a String object'); let anotherStrVal: String = String('Another String object');有几种方法可以检查给定变量是否包含字符串。通常,typeof 运算符用于检查原始字符串类型,instanceof 运算符可用于字符串对象实例。 除此之外,Object.prototype 属性可用于检查给定类型是否为字符串。 在 TypeScript 中使用 typeof 运算符检查变量是否为字符串typeof 是一个 TypeScript 一元运算符,它返回指定操作数的数据类型。 语法: typeof运算符返回一个表示操作数类型的字符串。 让我们创建一个原始字符串 userName。 let userName: string = 'Ricky hardy';接下来,我们将使用 typeof 运算符来检查 userName 变量的数据类型。让我们将它打印到控制台,如下所示: console.log(typeof userName);输出: string因此,typeof 运算符可用于检查条件代码片段中的原始类型字符串,如下所示: if (typeof userName === 'string') { // logic to be executed when the type is a string } else { // logic to be executed for non-string types } 在 TypeScript 中使用 instanceof 运算符检查变量是否为字符串instanceof 运算符对给定对象的原型链进行操作,并检查原型属性是否出现在那里。它检查指定对象是子对象还是给定构造函数的实例。 语法: instanceof该运算符返回一个布尔值。此外,运算符只接受对象实例,而不接受原语。 让我们实例化一个新的字符串对象 vehicleBrand。 let vehicleBrand: String = new String("AUDI");接下来,我们将使用 instanceof 运算符来检查 vehicleBrand 是否为字符串类型。 console.log(vehicleBrand instanceof String);输出: true正如预期的那样,运算符返回 true,因为 vehicleBrand 是一个字符串对象。 在 TypeScript 中使用 Object.prototype 检查变量是否为字符串Object.prototype 也可以用作在 TypeScript 中识别字符串类型的更通用的方法。该属性包含 toString() 方法,我们可以在其中使用 call 方法并检查指定变量原型的类型。 语法: Object.prototype.toString.call();这应该返回以下格式的字符串: "[object String]" OR "[object Array]" OR . . .让我们创建一个新变量 newStringValue。 let newStringValue: string = 'This is a new string';接下来,我们将使用 Object.prototype 属性检查 newStringValue 变量构造函数类型。 console.log(Object.prototype.toString.call(newStringValue));输出: [object String]正如预期的那样,类型是字符串。 |
CopyRight 2018-2019 实验室设备网 版权所有 |