当前位置:网站首页>Typescript advanced type (2)
Typescript advanced type (2)
2022-06-12 18:03:00 【Out of the autistic bird】
List of articles
TS Advanced type
class class
class Person {
age:number // 1. Specify the type
gender = ' male ' // 2. Set the default value , Automatically specify the type
}
const p = new Person()
// p The type of Person
Constructors
class Person {
age: number
gender: string
constructor(age: number,gender: string){
this.age = age
this.gender = gender
}
}
// Be careful :JS You can use constructors directly constructor()
// TS You need to specify the type of the attribute in the class first
// namely this.age Corresponding Person Class age: number
// age Corresponding constructor Medium age: number
Example method
class Point{
x = 10
y = 20
scale(n: number): void{
this.x *= n
this.y *= n
}
}
Implementation interface
// adopt implements Give Way class Implementation interface
// Implementing interfaces means Person Class must provide Singable All properties and methods specified by the interface
interface Singable{
sing(): void
}
class Person implements Singable{
sing(){
console.log('sing')
}
}
Modifier
- public( public ): Default , Can be accessed anywhere
class Animal{
public move(){
console.log('123')
}
}
- protected( The protected ): Only for its In the class and subclass where the declaration is located ( Non instance object ) so
class Animal{
protected move(){
console.log('123')
}
}
class Dog extends Animal{
bark(){
console.log('456')
this.move()
}
}
const a = new Animal()
a.move() // Report errors , Not visible in the instance object
private( Private ): Only in Visible in the current class ( Instance objects and subclasses are not visible )
readonly( Read only modifier ): Prevent attribute assignment outside the constructor ; Only attributes can be decorated , Cannot modify method
class Person{
readonly age: number = 18 // The default value is
constructor(age: number){
this.age = age // Assignment in constructor
}
}
// Assignment is not allowed anywhere else
Be careful :readonly and const It means the same thing , Can not be modified , So it's connected to const equally , If the initial value is directly assigned ( Do not specify type ), The data type becomes literal
class Person{
readonly age = 18
constructor(age: number){
this.age = age // Report errors , because this.age The data type is 18
}
}
Again ,readonly You can also use the interface 、 Objects, etc
Type compatibility
TS use Structured type system (duck typing): Type checking focuses on the shape of the value
Type compatibility between objects
More members can be assigned to less members
class Point {
x: number; y: number}
class Point3D {
x: number; y: number; z: number}
const p: Point = new Point3D()
// p Set to Point type , nevertheless Point3D Example
// TS Only check that the two structures are the same (Point3D Compatible Point), So the types are compatible
c#、Java Is used to indicate the type system , You can't write like this
Type compatibility between interfaces
Empathy , Interface 、 Functions are also compatible
interface Point {
x: number; y:number}
interface Point3D {
x: number; y:number; z: number}
let p1: Point
let p2: Point3D
P1 = P2
// Classes and interfaces are also compatible
class Point3D {
x: number; y:number; z: number}
let p3: Point = new Point3D()
Type compatibility between functions
Compatibility between functions should be considered : Number of parameters 、 Parameter type 、 return type
Contrary to the object rules, the main reason is to adapt to JS Function writing method of
Number of parameters : More parameters are compatible with less parameters ( Contrary to the object , Less parameters can be assigned to more )
// Because in JS in , It is common to omit unused function arguments , Therefore, the form that less parameters can be assigned to more parameters
type F1 = (a: number) => void
type F2 = (a: number,b: number) => void
let f1: F1
let f2: F2 = f1
Parameter type : The parameter types in the same location should be the same or compatible ( Contrary to the object , Parameters with fewer parameter types can be assigned to more )
interface Point2D {
x: number; y:number}
interface Point3D {
x: number; y:number; z: number}
type F2 = (p: Point2D) => void
type F3 = (p: Point3D) => void
let f2: F2
let f3: F3 = f2
return type : The return value of the function is in JS There is no special way to write , therefore There is no need to be the opposite of the object , If the object is returned , More members can be assigned to less members
type F5 = ()=>{
name: string}
type F6 = ()=>{
name: string; age: number}
let f5: F5
let f6: F6
f5 = f6
Cross type
Similar to interface inheritance extends, Sure Combine multiple types into one type
interface Name {
name: string}
interface Age {
age: number}
type PersonDetail = Person & Age
And interface inheritance : Interface inheritance will report an error for the conflict of attributes with the same name ; The cross type is acceptable for all types of conflicts
Generic
Ensure type safety Under the premise of , Let function, etc Working with multiple types , Realize reuse
Basic use
Application scenarios : We want a function to return whatever data it passes in ( Of course any Very convenient , But there is no guarantee of safety )
// Declare generic functions
function id<Type>(value: Type): Type {
return value}
// Call generic functions
const num = id<number>(10)
const str = id<string>('mkbird')
// TS Can automatically type inferences
const num = id(10) // Automatically infer 10 by number
- grammar : Add... After the function name < Type variable >, Type variable name is self-made
- Type variables deal with types, not values
- When called in <> Add specific data types to
Generic constraint
By default, generic variables can represent multiple types , This will result in no access to any properties
// because value There may be many types , So I can't access string Of length
function id<Type>(value: Type): Type {
console.log(value.length) // Report errors
return value
}
At this point, generic constraints are required , There are two main ways
- Specify more specific types
// The array must have length attribute , take value Of Type Change the type to array , The return value of Type The type is also changed to array
function id<Type>(value: Type[]): Type[] {
console.log(value.length)
return value
}
- Adding constraints (extends)
here extends It represents constraints , Not inheritance ; The constraint represents , The type of the incoming value must have length attribute
interface Length {
length: number}
function id<Type extends Length>(value: Type): Type {
console.log(value.length)
return value
}
Generic type variables can have multiple types , And type variables can also be constrained
// Create a function to get the value of the attribute in the object ( This attribute must exist in the object )
// keyof Type Used to receive objects , Generate the union type of its key
// In this example, you receive Person Of name and age, Union type is name | age
function getProp<Type,Key extends keyof Type>(obj: Type, key: Key){
return obj[key]
}
let person = {
name:'mkbird', age:18}
getProp(person,'name') //mkbird
// You can also receive methods of data types
getProp(18,'toFixed')
Generic interface
Interfaces can also be used with generics
interface Func<Type>{
id: (value: Type) => Type
fun: () => Type[]
}
// When using generic interfaces , The type of the generic must be specified
let obj: Func<number> = {
id(value) {
return value}
fun() {
return [1,2,3]}
}
Generic classes
class Add... After the name < Type variable >
class Number<NumType>{
defaultValue: NumType
add: (x: NumType,y: NumType) => NumType
}
const num = new Number<number>()
num.defaultValue = 10
// Cases that can be omitted when calling
class Number<NumType>{
defaultValue: NumType
add: (x: NumType,y: NumType) => NumType
constructor(value: NumType){
this.defaultValue = value
}
}
const num = new Number(10)
Generic tool types
For simplification TS Generic operations
Partial<Type>take Type All properties of are set to optional
interface Props {
id: sring
children: number[]
}
type PartialProps = Partial<Props>
// The structure of the new type constructed is the same as that of the original , Only the attribute becomes optional
Readonly<Type>take type All properties of are set to read-onlyPick<Type,keys>from Type Select a set of properties to construct a new type
interface Props {
id: sring
name: string
children: number[]
}
type PickProps = Pick<Props,'id' | 'name'>
Record<Keys,Type>Construct an object type , The key is Keys, The value is Type
type RecordObj = Record<'a' | 'b' | 'c', string[]>
// amount to
//type RecordObj = {
// a: string[]
// b: string[]
// c: string[]
//}
let obj: RecordObj = {
a: ['a'],
b: ['b'],
c: ['c']
}
Index signature type
When you can't determine which properties are in the object , Use the index signature type
Use [key: string] To constrain the implementation name appearing in the interface , such obj Any number of attributes can appear in the
// JS The key of the object in is string Type of
// key Just a placeholder , Can be replaced by other
interface AnyObject{
[key: string]: number
}
let obj: AnyObject = {
a: 1,
b: 2
}
Mapping type
Create a new type based on the old type ( object type )、 Improve development efficiency
Can only be used in type aliases , You cannot use... In an interface
type PropKeys = 'x' | 'y' | 'z'
type Type1 = {
[key in PropKeys]: number}
// Equivalent to
// type Type1 = {x: number;y: number;z: number}
Object based generation
type Props = {
a: number;b: string;c: boolean}
// One more step keyof Get object properties
// take a,b,c All become number
type Type3 = {
[key in keyof Props]: number}
Query type index
type Props = {
a: number;b: string}
type TypeA = Props['a'] // Inquire about a by number type
type Type = Props['a'|'b'] // number|string
type Type = Props[keyof Props] // number|string
边栏推荐
- Stream flow precautions
- SSM integrates FreeMarker and common syntax
- Leetcode 718 longest common substring
- Vant3+ts dropdownmenu drop-down menu, multi data can be scrolled
- Detailed description of SQL cursor and example of internal recycling
- 有关cookie的用法介绍
- leetcode 300. Longest increasing subsequence
- 一种好用、易上手的小程序IDE
- Office application cannot start normally 0xc0000142
- error接口原创
猜你喜欢

利用小程序快速生成App,只需七步

机器学习系列(3):Logistic回归

Extreme Programming -- Practice of root cause analysis

Eve-ng installation (network device simulator)

JS for Fibonacci sequence

High-Speed Layout Guidelines 未完...

ES7 does not use parent-child and nested relationships to implement one to many functions

Vant3+ts H5 pages are nested into apps to communicate with native apps

JDBC quick start tutorial

USB to serial port - maximum peak serial port baud rate vs maximum continuous communication baud rate
随机推荐
SSM集成FreeMarker以及常用语法
First principles of enterprise architecture
A story on the cloud of the Centennial Olympic Games belonging to Alibaba cloud video cloud
vant3+ts DropdownMenu 下拉菜单,数据多能滚动加载
USB转串口那些事儿—最大峰值串口波特率VS连续通信最高波特率
有源差分晶振原理圖以及LV-PECL、LVDS、HCSL區別
Random talk about redis source code 91
EASYCODE template
js二分法
vant3+ts+pinia tab选项卡列表页面点击进详情,详情页返回tab高亮在原位置,刷新高亮默认在第一项
JS dichotomy
Still using Microsoft office, 3 fairy software, are you sure you don't want to try?
Explanation of core interrupt of Godson processor
leetcode 647. Palindrome substring
Gospel of audio and video developers, rapid integration of AI dubbing capability
Message queuing MySQL tables that store message data
C operation database added business data value content case school table
js判断回文数
String s = null ; String s = new String(); String s = "; what is the difference between string s?
ESP-IDF 添加自己的组件