2020.2.26 补充泛型函数定义方式
function say(person: string, content: string): boolean {
if (person === '' || content === '') return false;
console.log(`${person}say:${content}`);
return true;
}
const somebody = {
say (person: string, content: string): boolean {
if (person === '' || content === '') return false;
console.log(`${person}say:${content}`);
return true;
}
};
泛型的使用为了方便复用函数——复用不同类型输入,但是行为和操作逻辑一致的函数。
function say(operate: T, person: string, content: string): boolean {
if (person === '' || content === '') return false;
console.log(`${person} ${operate}:${content}`);
return true;
}
函数表达式类型的写法有三种:
const say = function (person: string, content: string): boolean {
if (person === '' || content === '') return false;
console.log(`${person}say:${content}`);
return true;
};
补充——加入泛型的定义方式:
const say = function (person: string, content: string, operate: T): boolean {
if (person === '' || content === '') return false;
console.log(`${person}${operate}:${content}`);
return true;
};
type sayType = (person: string, content: string) => boolean;
var say: sayType = function (person, content) {
if (person === '' || content === '') return false;
console.log(`${person}say:${content}`);
return true;
};
补充——加入泛型的定义方式:
type sayType = (operate: T, person: string, content: string) => boolean;
var say: sayType = function (operate, person, content) {
if (person === '' || content === '') return false;
console.log(`${person} ${operate}:${content}`);
return true;
};
interface Say {
(person: string, content: string): boolean;
}
const say: Say = function (person, content) {
if (person === '' || content === '') return false;
console.log(`${person}say:${content}`);
return true;
};
补充——泛型接口的定义方式:
一种是放在接口大括号的外边,但是在使用接口的使用就一定要将实际用的类型穿进 <> 内。
type sayWhileSimiling = 'gegege' | 'hhhh';
interface Say {
(operate:T, person: string, content: string): boolean;
}
const say: Say = function (operate, person, content) {
if (person === '' || content === '') return false;
console.log(`${person}${operate}:${content}`);
return true;
};
一种是的在大括号内部,这种情况不需要在接口使用的时候就将实际用的类型穿进去,而是在实际函数调用时再传入。
interface Say {
(operate:T, person: string, content: string): boolean;
}
const say: Say = function (operate, person, content) {
if (person === '' || content === '') return false;
console.log(`${person}${operate}:${content}`);
return true;
};
箭头函数通常写成函数表达式的形式:
const say = () => {};
所以箭头函数的类型定义,就与函数表达式的非常相似,完全可以使用上边的三种方法定义类型,这里就写出嵌入函数里边的写法:
const say = (person: string, content: string): boolean => {
if (person === '' || content === '') return false;
console.log(`${person}say:${content}`);
return true;
};
补充——箭头函数的泛型定义方式:
const say = (operate:T, person: string, content: string): boolean => {
if (person === '' || content === '') return false;
console.log(`${person}${operate}:${content}`);
return true;
};
总结:好像函数声明式及其衍生形式只能采用嵌入函数里边的写法,而函数表达式的写法有很多种,比较灵活。