- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
**摘要:**在本文中,回顾了TypeScript中几个最有用的类型保护,并通过几个例子来了解它们的实际应用。
本文分享自华为云社区《如何在TypeScript中使用类型保护》,作者:Ocean2022。
类型保护是一种TypeScript技术,用于获取变量类型信息,通常使用在条件块语句中。类型守卫是返回布尔值的常规函数,接受一个类型并告诉TypeScript是否可以缩小到更具体的类型。类型保护具有唯一的属性,可以确保测试的值是根据返回的布尔值设置的类型。
TypeScript使用了一些内置的JavaScript操作符,比如typeof、instanceof和in操作符,这些操作符用于确定一个对象是否包含属性。类型保护可以让你指导TypeScript编译器在特定的上下文中推断出变量的特定类型,确保参数的类型与你所说的一致。
类型保护通常用于缩小类型,它非常类似于特征检测,允许您检测值的正确方法、原型和属性。因此,您可以轻松地找出如何处理该值。
有五种主要的方式来使用类型保护:
在本文中,我们将探索上面列出的 5 种方法。让我们开始吧!
Instanceof是一个内置类型保护器,可用于检查一个值是否是给定构造函数或类的实例。有了这个类型保护,我们可以测试一个对象或值是否派生自一个类,这对于确定实例类型的类型很有用。
instanceof类型保护的基本语法如下:
objectVariable instanceof ClassName;
在下面的例子中,我们看到了一个instanceof类型保护的例子:
interface Accessory {
brand: string;
}
class Necklace implements Accessory{
kind: string;
brand: string;
constructor(brand: string, kind: string) {
this.brand = brand;
this.kind = kind;
}
}
class bracelet implements Accessory{
brand: string;
year: number;
constructor(brand: string, year: number) {
this.brand = brand;
this.year = year;
}
}
const getRandomAccessory = () =>{
return Math.random() < 0.5 ?
new bracelet('cartier', 2021) :
new Necklace('choker', 'TASAKI');
}
let Accessory = getRandomAccessory();
if (Accessory instanceof bracelet) {
console.log(Accessory.year);
}
if (Accessory instanceof Necklace) {
console.log(Accessory.brand);
}
上面的getRandomAccessory函数返回一个Necklace或bracelet对象,因为它们都实现了Accessory接口。Necklace和bracelet的构造函数签名是不同的,用instanceof比较两个构造函数签名可以有效地确定类型。
typeof类型保护是用来确定变量的类型。typeof的类型保护据说是非常有限和浅薄的。它只能确定以下JavaScript能识别的类型:
对于这个列表之外的任何内容,typeof类型保护只返回object。
typeof类型保护可以用以下两种方式编写:
typeof v !== "typename"
#or
typeof v === "typename"
typename可以是字符串、数字、符号或布尔值。
在下面的示例中,StudentId有一个string|number类型联合参数条目。我们看到,如果变量是string,则输出Student,如果是number,则输出Id。typeof类型保护符帮助我们从x参数中提取类型:
function StudentId(x: string | number) {
if (typeof x == 'string') {
console.log('Student');
}
if (typeof x === 'number') {
console.log('Id');
}
}
StudentId(`446`); //prints Student
StudentId(446); //prints Id
in类型保护检查对象是否具有特定的属性,并使用该属性区分不同的类型。它通常返回一个布尔值,表示该属性是否存在于该对象中。它用于其缩小范围,以及检查浏览器支持。
in类型保护的基本语法如下:
propertyName in objectName
在下面的例子中,in类型守卫检查 house 属性是否存在。如果存在,则返回布尔值true,如果不存在,则返回false。
"house" in { name: "test", house: { parts: "door" } }; // => true
"house" in { name: "test", house: { parts: "windows" } }; // => true
"house" in { name: "test", house: { parts: "roof" } }; // => true
"house" in { name: "test" }; // => false
"house" in { name: "test", house: undefined }; // => true
下面是in类型保护的另一个类似例子:
interface Pupil {
ID: string;
}
interface Adult {
SSN: number;
}
interface Person {
name: string;
age: number;
}
let person: Pupil | Adult | Person = {
name: 'Britney',
age: 6
};
const getIdentifier = (person: Pupil | Adult | Person) => {
if ('name' in person) {
return person.name;
}
else if ('ID' in person) {
return person.ID
}
return person.SSN;
}
等式收缩保护器检查表达式的值。为了使两个变量相等,两个变量必须是同一类型的。如果一个变量的类型未知,但它等于另一个具有精确类型的变量,那么Typescript会使用该已知变量提供的信息来缩小第一个变量的类型:
function getValues(a: number | string, b: string) {
if(a === b) {
// this is where the narrowing takes place. narrowed to string
console.log(typeof a) // string
} else {
// if there is no narrowing, type remains unknown
console.log(typeof a) // number or string
}
}
如果变量a等于变量b,那么两者必须具有相同的类型。在这种情况下,Typescript把它缩小到字符串。如果没有收缩,a的类型仍然不明确,因为它可以是数字或字符串。
创建一个自定义类型守卫通常是使用类型守卫的强大选项。当您通过自己编写来创建自定义类型保护时,可以检查的内容没有限制。但是,如果自定义类型保护被错误地编写,它可能会带来很多错误。因此,精度是关键。
一个自定义类型保护的例子如下所示:
interface Necklace{
kind: string;
brand: string;
}
interface bracelet{
brand: string;
year: number;
}
type Accessory = Necklace | bracelet;
const isNecklace = (b: Accessory): b is Necklace => {
return (b as Necklace).kind !== undefined
}
const Necklace: Accessory = {kind: "Choker", brand: "TASAKI"};
const bracelet: Accessory = {brand: "Cartier", year: 2021};
console.log(isNecklace(bracelet)) //Logs false
console.log(isNecklace(Necklace)) //Logs true
在上面的代码中,类型谓词b是Necklace,这会让TypeScript将类型缩减为Necklace,而不是只返回一个布尔值。
TypeScript类型保护有助于确保类型的值,改善整体的代码流。在本文中,我们回顾了TypeScript中几个最有用的类型保护,并通过几个例子来了解它们的实际应用。
大多数时候,您的用例可以使用instanceof类型保护、tyoeof的类型保护或in类型保护来解决,然而,您可以在绝对必要的时候使用自定义类型保护。
我知道这有点愚蠢,但我需要保护 javascript,从某种意义上说,我希望增加尽可能多的安全性,以免它被盗版。好吧,因为它是系统的核心组件。我打算用YUI compressor来压缩混淆。 但我还想
因此,当我的宏运行时,我有这些简单的子程序可以解除保护而不是保护东西,唯一的问题是我的一些工作表实际上是图表,并且在调用这些子程序时它们没有得到保护。如何更改我的代码以合并图表?谢谢! Sub Unp
有很多关于 preventing CSRF 的文章. 但我就是不明白:为什么我不能只解析目标页面表单中的 csrf token 并将其与我的伪造请求一起提交? 最佳答案 如果您能够将脚本代码注入(in
关闭。这个问题是off-topic .它目前不接受答案。 想改善这个问题吗? Update the question所以它是 on-topic对于堆栈溢出。 9年前关闭。 Improve this q
我正在使用一个包含用于docker创建的敏感信息的env文件。 但问题是它们并不安全。可以通过docker inspect轻松查看它们,因此,任何可以运行docker命令的用户都可以使用它们。 我正在
NSA在此处提供了保护.NET框架2.0版的指南:http://www.nsa.gov/ia/_files/app/I731-008R-2006.pdf 我想知道他们是否提供更高版本的指南,例如版本3
我编写了一个 Java 应用程序,并计划在线发布它。每个版本都将使用我制作的 secret 序列 key 锁定。 我需要从反编译器等保护我的 jar 文件。这是我到目前为止所做的: 用户在表格中输入他
我不知道为什么这不起作用。如果 ?Session=2 不是您发出的,那么您将返回您的帐户。 这是我的代码: query("SELECT * FROM user_host WHERE uid = '"
我是 elasticsearch 的新手,但我非常喜欢它。我唯一找不到也无法完成的是保护生产系统的 Elasticsearch 。我读了很多关于在 elasticsearch 前使用 nginx 作为
假设我有以下头文件: #ifndef TESTCLASS_H #define TESTCLASS_H #include class TestClass { public: TestClass
在 C++ 中,我有一个基类 A,一个子类 B。两者都有虚方法 Visit。我想在 B 中重新定义“访问”,但 B 需要访问每个 A(以及所有子类)的“访问”功能。 我有类似的东西,但它告诉我 B 无
我目前正在使用 Apache FOP 库生成 PDF。我希望这些 PDF 免受复制粘贴,因此人们必须使用实际的 OCR 库(或手动输入)来获取 PDF 上的信息。 FOP 显然提供了一些安全性,然后将
我有一个使用 JSONP 进行跨域 ajax 调用的脚本。这很好用,但我的问题是,有没有办法阻止其他站点访问这些 URL 并从中获取数据?我基本上想制作一个允许的站点列表,并且只返回列表中的数据。我正
我在基于 Html/Javascript 构建的 Web 应用程序上使用了一些全局变量。我跨页面(或部分页面)使用这些变量,有时它们用作 ajax 调用的发布数据。我的问题是:这有多安全?当然,我可以
我有一个扩展到多个类文件的大项目。这个项目是在赶时间前匆忙完成的。这对项目安全造成了影响。所以简单来说,理论上任何人都可以在我的项目中调用一个 AJAX 脚本并让它运行,因为脚本中的函数不是用户权限感
相当多的人对 ivé 发送给他们的 dll 真正感兴趣,他们不是那种应该经常免费赠送的类型... 我只是想知道,如果我要出售我的组件、用户控件等,我将如何在所有权/加密代码(如果可能)等方面保护它们。
我正在开发一个 PHP 库,我们将在其中为客户提供加密代码。该代码将包括一个他们可以实例化的主要类,该类将处理许可证验证并公开其使用方法。主类将实例化几个子类,每个子类都包含在自己的文件中。我怎样才能
我有一个以 VUEJS 作为前端的 Laravel 应用程序,我通过创建 API 路由获取数据。因此,例如获取帖子数据的路线将是 http://localhost/api/posts 保护路线的最佳方
在许多网页上,我们都包含外部脚本。无论是类似于 Facebook 的按钮、用于分析或广告系统的客户端代码、外部评论提供商还是其他东西。 那些脚本无法访问我的 Ajax 资源,因为一直在检查原始 hea
我目前正在使用 PHP/MySQL 开发一个公开和开放源代码的软件。我在一个文件夹中有几个重要的 SECRET TXT 文件。我在软件中使用它们,但问题是它们也可以被任何知道文件夹和文件名的人读取:
我是一名优秀的程序员,十分优秀!