TypeScript:允许类型作为包含某些键的函数的参数
TypeScript: Allow types as parameter of function that contain certain keys
假设我有两个接口。
interface AppleReport {
name: string,
color: string,
age: string
}
interface BananaReport {
name: string,
color: string,
amount: number,
}
现在我定义一个函数。我希望此函数采用具有 name 键和 color 键的每种类型。
cosnt doSth = (value: **TODO**) => {
// do sth with *value* that contains *name* and *color*
}
我知道,我可以创建一个界面
interface dummyInterface {
name: string,
color: string,
}
并让 AppleReport 和 BananaReport 扩展它,但我想在函数类型定义中完成所有逻辑。
有什么想法吗?
你可以
cosnt doSth = (value: { name : string, color : string } ) => {
// do sth with *value* that contains *name* and *color*
}
但这看起来很乱,建议采用您不希望的方式创建一个接口,然后从中扩展其他 2 个接口。
或者如果您不想扩展其他接口,您可以只使用接口类型作为传入类型而不扩展。只要成员存在,它就仍然有效。
interface NameAndColor {
name: string,
color: string,
}
interface AppleReport {
name: string,
color: string,
age: string
}
interface BananaReport {
name: string,
color: string,
amount: number,
}
const doSth = (value: NameAndColor) => {
// do sth with *value* that contains *name* and *color*
}
let obj = { name : "myName", color : "myColor"};
doSth( obj );
但在我看来,真正最好的方法是扩展接口。
假设我有两个接口。
interface AppleReport {
name: string,
color: string,
age: string
}
interface BananaReport {
name: string,
color: string,
amount: number,
}
现在我定义一个函数。我希望此函数采用具有 name 键和 color 键的每种类型。
cosnt doSth = (value: **TODO**) => {
// do sth with *value* that contains *name* and *color*
}
我知道,我可以创建一个界面
interface dummyInterface {
name: string,
color: string,
}
并让 AppleReport 和 BananaReport 扩展它,但我想在函数类型定义中完成所有逻辑。
有什么想法吗?
你可以
cosnt doSth = (value: { name : string, color : string } ) => {
// do sth with *value* that contains *name* and *color*
}
但这看起来很乱,建议采用您不希望的方式创建一个接口,然后从中扩展其他 2 个接口。
或者如果您不想扩展其他接口,您可以只使用接口类型作为传入类型而不扩展。只要成员存在,它就仍然有效。
interface NameAndColor {
name: string,
color: string,
}
interface AppleReport {
name: string,
color: string,
age: string
}
interface BananaReport {
name: string,
color: string,
amount: number,
}
const doSth = (value: NameAndColor) => {
// do sth with *value* that contains *name* and *color*
}
let obj = { name : "myName", color : "myColor"};
doSth( obj );
但在我看来,真正最好的方法是扩展接口。