当前位置:网站首页>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
边栏推荐
- TypeScript高级类型(二)
- General differences between SQL server versions released by Microsoft in different periods so far, for reference
- USB to serial port - serial port driver type
- SSM integrates FreeMarker and common syntax
- Random talk about redis source code 90
- High speed layout guidelines incomplete
- A method of quickly reusing wechat login authorization in app
- Leetcode491 increasing subsequence
- Nixos 22.05 installation process record
- Section qemu+gdb
猜你喜欢

消息队列存储消息数据的 MySQL 表格

C operation database added business data value content case school table

High speed layout guidelines incomplete

Continued 2 asp Net core router basic use demonstration 0.2 acquisition of default controller data

js求斐波那契数列

Write a select based concurrent server

Schéma de cristallisation différentielle active et différence entre LV - PECL, LVDS et hcsl

C#的变量

Still using Microsoft office, 3 fairy software, are you sure you don't want to try?

Eve-ng installation (network device simulator)
随机推荐
Project training of Software College of Shandong University - Innovation Training - network attack and defense shooting range experimental platform of Software College of Shandong University (XXV) - p
Leetcode 718 longest common substring
TypeScript常用类型(一)
leetcode 300. Longest increasing subsequence
Use the official go Library of mongodb to operate the original mongodb
C#的变量
leetcode 647. Palindrome substring
C operation database added business data value content case school table
C business serial number rule generation component
Explanation of core interrupt of Godson processor
Advanced mountain -asp Net core router basic use demo 0.1
USB转串口那些事儿—最大峰值串口波特率VS连续通信最高波特率
Reconstruction -- sort out and decompose the inheritance system
When openharmony meets openeuler
JDBC several pits
Original error interface
Window版本pytorch入门深度学习环境安装与配置
vant3+ts+pinia tab选项卡列表页面点击进详情,详情页返回tab高亮在原位置,刷新高亮默认在第一项
迄今微软不同时期发布的SQL Server各版本之间的大致区别,供参考查阅
String s = null ; String s = new String(); String s = "; what is the difference between string s?