typescript TS Generic

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript TS Generic相关的知识,希望对你有一定的参考价值。

//Simple Generic
function echo(data:any){
	return data;
}

console.log(echo("Max").length); //Can put method also
//However, IDE did not show length method which means it did not know that the function returned is a string

//Bottom if put length will show undefined instead of compilation error
console.log(echo(27));
console.log(echo({name:"Max", age: 27}));

//Objective: let TS know that although accept generic data, but can know the type returned from it

//Better Generic
function betterEcho<T>(data: T){ //Makes it a generic function, can be any character
	return data;
}
//Telling TS when using this function, give us the type so that we can use the type in the parameters
console.log(betterEcho("Max").length); //Will show the method
console.log(betterEcho<number>(27)); //Will not have this method and will show the error
console.log(betterEcho({name:"Max", age: 27}));


//Built-in Generics
//1. Arrays
const testResults: Array<number> = [1.94, 2.33];
testResults.push(1); //works
testResults.push("string") //wrong

//2. Assign Generic Type to be an Array
function printAll<T>(args: T[]){
	args.forEach( el => console.log(el));
}
printAll<string>(["Apple", "Banana"])

//Generic Types
const echo2: <T>(data:T) => T = echo;
console.log(echo2<string>("Something"));

//Generic Class
//Problem
class SimpleMath {
	baseValue;
	multiplyValue;
	calculate(){
		return this.baseValue * this.multiplyValue;
	}
}

const simpleMath = new SimpleMath();
simpleMath.baseValue = 10; //if change to "something", no compilation error
simpleMath.multiplyValue = 20;
console.log(simpleMath.calculate());

//Solution - change to generic class
class SimpleMath<T> {
	baseValue: T;
	multiplyValue: T;
	calculate(): number{
		return +this.baseValue * +this.multiplyValue; //explicitly cast the value "+"
	}
}

const simpleMath = new SimpleMath();
simpleMath.baseValue = 10; //if changed to "something", no compilation error
simpleMath.multiplyValue = 20;
console.log(simpleMath.calculate());

//Solution 2
class SimpleMath<T extends number | string> { //set a costraint and then add option of string and if given "10", will cast to Number
	baseValue: T;
	multiplyValue: T;
	calculate(): number{
		return +this.baseValue * +this.multiplyValue; //explicitly cast the value "+"
	}
}
const simpleMath = new SimpleMath<number>();
class SimpleMath<T extends number | string, U extends number | string> { 
	baseValue: T;
	multiplyValue: U;
	calculate(): number{
		return +this.baseValue * +this.multiplyValue;
	}
}
const simpleMath = new SimpleMath<string, number>();
simpleMath.baseValue = "10";
simpleMath.multiplyValue = 20;
console.log(simpleMath.calculate());
 

以上是关于typescript TS Generic的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript 的 generic 区别是什么?

typescript typescript1.ts

[TypeScript 基础系列] TypeScript 的安装以及编写第一个 TS 文件

Ts/Typescript基础运用

Ts/Typescript基础运用

TypeScript系列教程04编译参数