Typescript 正确键入Box类
我正在学习使用PureScript进行函数式编程。在JavaScript中,有一个框的示例如下所示:Typescript 正确键入Box类,typescript,Typescript,我正在学习使用PureScript进行函数式编程。在JavaScript中,有一个框的示例如下所示: const Box = x => ({ map: f => Box(f(x)), fold: f => f(x), inspect: () => `Box(${x})` }); 我想使用TypeScript键入以下代码,以便对如下代码进行语法检查: const nextCharForNumberString = str => Box(
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
我想使用TypeScript键入以下代码,以便对如下代码进行语法检查:
const nextCharForNumberString = str =>
Box(str)
.map(s => s.trim())
.map(s => new Number(s))
.map(i => i + 1)
.map(i => String.fromCharCode(i))
.fold(c => c.toLowerCase());
interface IBox<T> {
map: <U>(T) => IBox<U>;
fold: <U>(T) => U;
inspect: (T) => string;
}
const Box: <T>(x: T) => IBox<T> = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
我尝试按如下方式键入此框:
const nextCharForNumberString = str =>
Box(str)
.map(s => s.trim())
.map(s => new Number(s))
.map(i => i + 1)
.map(i => String.fromCharCode(i))
.fold(c => c.toLowerCase());
interface IBox<T> {
map: <U>(T) => IBox<U>;
fold: <U>(T) => U;
inspect: (T) => string;
}
const Box: <T>(x: T) => IBox<T> = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
接口IBox{
map:(T)=>IBox;
折叠:(T)=>U;
检查:(T)=>字符串;
}
常量框:(x:T)=>IBox=x=>({
map:f=>Box(f(x)),
折叠:f=>f(x),
检查:()=>`Box(${x})`
});
如何正确键入Box函数让我感到困惑。为了简化语法,我也尝试了以下方法:
function Box<T>(x: T): IBox<T> {
return {
map: <U>(f): IBox<U> => Box(f(x)),
fold: <U>(f): U => f(x),
inspect: () => `Box(${x})`
};
}
功能框(x:T):IBox{
返回{
map:(f):IBox=>Box(f(x)),
折叠:(f):U=>f(x),
检查:()=>`Box(${x})`
};
}
我所有的尝试都没有成功。我希望在编译时捕获以下内容:
const s: IBox<String> = Box(5)
.map(x => x * x)
.map(x => x.toString())
.map(x => x * x)
.fold(x => x);
常量s:IBox=Box(5)
.map(x=>x*x)
.map(x=>x.toString())
.map(x=>x*x)
.折叠(x=>x);
在我看来,这在TypeScript中是可能的。如有任何见解,将不胜感激 当然,我想你已经很接近了。以下是键入
框
界面的方法:
interface Box<T> {
map<U>(f: (t: T) => U): Box<U>;
fold<U>(f: (t: T) => U): U;
inspect(): string;
}
然后,您将在编译时捕获问题,如您所愿:
const badS = Box(5)
.map(x => x * x)
.map(x => x.toString())
.map(x => x * x) // error, x is a string, you cant multiply it
.fold(x => x);
并且能够修复它:
const goodS = Box(5)
.map(x => x * x)
.map(x => x.toString())
.fold(x => x); // goodS is type string
console.log(goodS); "25"
希望有帮助;祝你好运