当前位置:网站首页>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 .
边栏推荐
- "Digital security" alert NFT's seven Scams
- 面试8家公司,1周拿了5个offer,分享一下自己的心得
- MySQL tutorial 67- filter duplicate data using distinct
- 行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化
- 微信小程序
- R语言偏相关性计算(Partial Correlation)、使用ggm包的pcor函数计算偏相关性(Partial Correlations)
- MySQL教程67-使用DISTINCT过滤重复数据
- Huawei 2023 starts to warm up in advance! Zuo Shen's program code interview guide comes in handy
- R语言ggplot2可视化线图(line)、自定义配置标题文本相关内容颜色和图例(legend)颜色相匹配(和分组线图的颜色相匹配、match colors of groups)
- 30行自己写并发工具类(Semaphore, CyclicBarrier, CountDownLatch)
猜你喜欢

Redis distributed lock, it's really impossible without it

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

Okaleido上线聚变Mining模式,OKA通证当下产出的唯一方式

Solve the vender-base.66c6fc1c0b393478adf7.js:6 typeerror: cannot read property 'validate' of undefined problem

面试8家公司,1周拿了5个offer,分享一下自己的心得

Wavelet transform --dwt2 and wavedec2

如何构建面向海量数据、高实时要求的企业级OLAP数据引擎?

Implementation of recommendation system collaborative filtering in spark

CVPR 2022 | in depth study of batch normalized estimation offset in network

LeetCode - 380 O(1) 时间插入、删除和获取随机元素 (设计 哈希表+数组)
随机推荐
Wavelet transform --dwt2 and wavedec2
CircleIndicator组件,使指示器风格更加多样化
Understand "average load"
Ml image depth learning and convolution neural network
活动回顾|7月6日安远AI x 机器之心系列讲座第2期|麻省理工教授Max Tegmark分享「人类与AI的共生演化 」
MySQL全局锁
mysql意向锁
MySQL - user and permission control
MySQL-自增锁
Solve the vender-base.66c6fc1c0b393478adf7.js:6 typeerror: cannot read property 'validate' of undefined problem
Pytoch learning notes -- Summary of common functions 3
Leetcode - 232 realize queue with stack (design double stack to realize queue)
物理防火墙是什么?有什么作用?
LeetCode - 232 用栈实现队列 (设计 双栈实现队列)
How to solve cross domain problems
General test case writing specification
How to disable hosting when Flink SQL in flink-1.13.6 runs in yarn session mode
MySQL—常用SQL语句整理总结
HDD Hangzhou station · harmonyos technical experts share the features of Huawei deveco studio
Record Locks(记录锁)