当前位置:网站首页>Typescript learning 2 - Interface
Typescript learning 2 - Interface
2022-07-25 16:01:00 【Gai Yuexi's boyfriend outside the circle (kuaixi)】
Catalog
Ways to bypass additional attribute checks
explain
This article learns from the article of the great God of gold digging https://juejin.cn/post/7003171767560716302, The original author is the great rabbit God .
Interface
Specify and restrict the format of types .
In the original text, the duck type identification method is mentioned , namely , If the object passed in has the required attributes, it is considered to meet the requirements .
for instance :
function getName(obj: { name: string }) {
return obj.name;
}
// console.log(getName({ name: 'Jack', age: 11 }));// Report errors , Because there is one more age attribute
// console.log(getName({ name: 'Jack' }));// correct
let myObj = { name: 'Jack', age: 123 };
console.log(getName(myObj));// correct Find out , When calling a function, directly pass in parameters , The required fields must fully comply with , No more, no less .
And if you define object variables first , Then call the function to pass in variables , Then you can have some more attributes . This means that , Assignment makes type checking loose . Because when assigning values ,myObj The assigned type will be automatically inferred , amount to :
let myObj: { name: string, age: number } = { name: 'Jack', age: 123 };Then the function is called. , take myObj Assign to obj, At this time, the duck type discrimination method will be adopted , Both have name attribute , So I think it's the same type .
Then use the interface to write :
interface IObj {
name: string
}
function getName(obj: IObj) {
return obj.name;
}
// console.log(getName({ name: 'Jack', age: 11 }));// Report errors , Because there is one more age attribute
// console.log(getName({ name: 'Jack' }));// correct
let obj = { name: 'Jack', age: 123 };
console.log(getName(obj));// correct Same effect .
Be careful , stay type、interface Commas can be used in 、 A semicolon ,class Comma cannot be used in .
Optional attribute
Some optional attributes can be defined in the interface .
interface IPerson {
id: number;
name: string;
age?: number;
gender: string;
}Read-only property
Some properties are read-only , Do not modify , You can only change the value of an object when it is just created .
interface IPerson {
readonly id: number;
name: string;
age?: number;
gender: string;
}
let p: IPerson = { id: 1, name: 'Tom', gender: 'M' }
// p.id = 2;// Report errors And const Different , For reference types ,const It can only ensure that the user cannot modify the reference address , But the internal properties can be modified . but readonly Decorated attributes , All internal data cannot be modified .
readonly When modifying the type of variable , Only arrays and tuples are allowed to be decorated .
let o: readonly object = { name: 'hello' }// error
let arr: readonly number[] = [1, 2, 3]// Sure Read only array
mention readonly, Just say ReadonlyArray. It can declare read-only arrays , The elements of the array cannot be modified .
let arr: ReadonlyArray<number> = [1, 2, 3]
// arr[0] = 23// Report errors
// arr.push(56)// Method removed , therefore arr.push It doesn't exist
// arr.length = 15// Do not modify the
let arr2: number[] = []
// arr2 = arr// Cannot be assigned to an ordinary array
arr2 = arr as number[]// Only type assertions can be used When declaring a type ,ReadonlyArray<number> and readonly number[] It is equivalent. .
Ways to bypass additional attribute checks
1、 Previously mentioned assignment
2、 Types of assertions
Type assertion is to tell TS, I think it's this type , therefore TS There will be no additional inspection .
interface IPerson {
readonly id: number;
name: string;
age?: number;
gender: string;
}
// let p: IPerson = { id: 1, name: 'Tom', gender: 'M', city: 'Shanghai' }// Report errors
let p: IPerson = { id: 1, name: 'Tom', gender: 'M', city: 'Shanghai' } as IPerson;// Sure 3、 Index signature
Index signature
Index signature is an arbitrary attribute , contain string and number Two types of .
Once any property is defined , Then the type of the determined attribute and the optional attribute must be a subset of its type , Because certain attributes and optional attributes are also considered as one of any attributes .
interface IF {
name: string;
// id: number;// Report errors , because number No string Subtypes of
[prop: string]: string;
}
let m: IF = { name: 'Jack', h: 'hello' }When using any attribute of two types at the same time , The return value of a numeric index must be a subtype of the return value type of a string index .
interface IF {
name: string;
// id: number;// Report errors , because number No string Subtypes of
[prop1: string]: string;
// [prop2: number]: number// Report errors , Because of the return value number No string Subtypes of
[prop2: number]: string
}
let m: IF = { name: 'Jack', h: 'hello', 1: 'hello' }Inheritance of interfaces
interface IPerson {
name: string
}
interface IStudent extends IPerson {
id: number
}
let st: IStudent = { name: 'Jack', id: 1 }Interface allows multiple inheritance .
interface IPerson {
name: string
}
interface IAnimal {
class: string
}
interface IStudent extends IPerson, IAnimal {
id: number
}
let st: IStudent = { name: 'Jack', id: 1, class: 'person' }stay TS in , If two or more parent interfaces of multiple inheritance have the same properties , But the types of definitions are different , May be an error .
It's not a mistake :
interface IPerson {
name: string;
city: string
}
interface IAnimal {
class: string;
city: string
}
interface IStudent extends IPerson, IAnimal {
id: number
}
let st: IStudent = { name: 'Jack', id: 1, class: 'person', city: 'Shanghai' }Report a mistake like this :
interface IPerson {
name: string;
city: string
}
interface IAnimal {
class: string;
city: number
}
interface IStudent extends IPerson, IAnimal {// Report errors
id: number
}
let st: IStudent = { name: 'Jack', id: 1, class: 'person', city: 'Shanghai' }therefore , You need to ensure that there is no common attribute or the type of common attribute is the same among multiple parent interfaces .
边栏推荐
- Leetcode - 225 implements stack with queue
- R语言ggplot2可视化线图(line)、自定义配置标题文本相关内容颜色和图例(legend)颜色相匹配(和分组线图的颜色相匹配、match colors of groups)
- ServletConfig 类和ServletContext 类
- Leetcode - 677 key value mapping (Design)*
- Why is preparestatement better and safer?
- R语言偏相关性计算(Partial Correlation)、使用ggm包的pcor函数计算偏相关性(Partial Correlations)
- 开发者如何为React Native选择合适的数据库
- MySQL 元数据锁(MDL)
- MySQL教程65-MySQL操作表中数据
- I want to ask whether the variable configuration function can only be used in SQL mode
猜你喜欢

HDD Hangzhou station · harmonyos technical experts share the features of Huawei deveco studio

Huawei 2023 starts to warm up in advance! Zuo Shen's program code interview guide comes in handy

推荐系统-协同过滤在Spark中的实现

【莎士比亚:保持做人的乐趣】

不愧是阿里内部“千亿级并发系统架构设计笔记”面面俱到,太全了

How matlab saves all the data after running

开发者如何为React Native选择合适的数据库

LeetCode - 359 日志速率限制器 (设计)

LeetCode - 677 键值映射(设计)*

How matlab produces random complex sequences
随机推荐
LeetCode - 380 O(1) 时间插入、删除和获取随机元素 (设计 哈希表+数组)
用GaussDB(for Redis)存画像,推荐业务轻松降本60%
[server data recovery] data recovery cases of raid information loss caused by unexpected power failure of HP EVA server storage
LeetCode - 641 设计循环双端队列(设计)*
共2600页!又一份神级的面试手册面世~
IDEA—点击文件代码与目录自动同步对应
Leetcode - 362 knock counter (Design)
一文入门Redis
Geogle colab notes 1-- run the.Py file on the cloud hard disk of Geogle
【莎士比亚:保持做人的乐趣】
BSC smart chain contract mode system development details
LeetCode - 303 区域和检索 - 数组不可变 (设计 前缀和数组)
今天睡眠质量记录84分
Ml image depth learning and convolution neural network
TypeError: Unrecognized value type: <class ‘str‘> ParserError: Unknown string format
对this对象的理解
Recommended collection, which is probably the most comprehensive coding method summary of category type features
mysql意向锁
Pytoch framework exercise (based on kaggle Titanic competition)
Redis分布式锁,没它真不行