TypeScript インターフェイスとその一般的な用途

tsのインターフェースは何ですか?

  • オブジェクト内の属性データを修飾または制約するためのオブジェクト タイプとして使用されます。
interface IPerson{
    
    
	name: string,
	age: number,
	sex: string,
}
let person: IPerson{
    
    
	name: 'xxxxx',
	age: 0,
	sex: 'man',
}

インターフェイスとオブジェクト内のプロパティの間には 1 対 1 の対応が必要です。そうでない場合はエラーが報告されます。

読み取り専用タイプ: 読み取り専用

interface IPerson{
    
    
	readonly name: string,
}
let person: IPerson{
    
    
	name: 'myName',
}
person.name = 'newName' // 报错,因为只读

オプションのタイプ: ?

interface IPerson{
    
    
	name?: string, // 可有可无类型,当person对象无name属性的时候也不会报错
}
let person: IPerson{
    
    
	// 为空
}
person.name = 'newName' // ‘newName’

関数の種類: (関数パラメータ): 戻り値

interface IFunction{
    
    
	(name: string, age: number): boolean // 括号里的数函数参数,后面为函数返回值
}
let newFunction: IFunction = function (name: string, age: number): boolean {
    
    
	// 括号里的数函数参数,后面为函数返回值	
	return age > 1
}
console.log(newFunction(('myName', 2)), // true

インターフェース継承インターフェース: 拡張

  • 他のインターフェイスのコンテンツを継承できるインターフェイス myHobby を定義し、extends を使用します。
interface IRunning{
    
    
	run(): void
}
interface ISwimming{
    
    
	swimming(): any
}
interface myHobby extends IRunning, ISwimming {
    
    }

クラス クラス型: 実装する

  • クラスはインターフェイスを通じて現在のクラスの型を定義できます。
  • これを実現するには、implements キーワードを使用します。
interface IRunning{
    
    
	run(): void
}
interface ISwimming{
    
    
	swimming(): any
}
interface myHobby extends IRunning, ISwimming {
    
    }

class MyClass implements myHobby {
    
    
	run(){
    
    
		console.log('我可以跑....')
	},
	swimming(){
    
    
		console.log('我可以游泳')
	}
}
let myObj = new MyClass()
myObj.run()
myObj.swimming()

おすすめ

転載: blog.csdn.net/weixin_44684357/article/details/132051322