- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Typescript能够执行简单的功能组合吗?我写出了以下基本实现,以进行组合,映射和筛选以进行测试。
类型和功能在下面设置,然后在之后实现。
javascript似乎不错,但是使用compose
时,打字稿显示出误报。具体来说,似乎可以理解第一个函数将要返回的内容,但随后它不会将该信息传递给第二个函数的输入。设置后在下面进一步解释。
import { curry } from './curry'
type f1<a, b> = (a: a) => b
type f2_2<a, b, c> = (a: a, b: b) => c
type f2_1<a, b, c> = (a: a) => (b: b) => c
type f2<a, b, c> = f2_2<a, b, c> & f2_1<a, b, c>
type p<a> = (a: a) => boolean
//====[compose]================================
type b3 = <a, b, c>(f: f1<b, c>, g: f1<a, b>, a: a) => c
type b2 = <a, b, c>(f: f1<b, c>, g: f1<a, b>) => f1<a, c>
type b1 = <a, b, c>(f: f1<b, c>) => f2<f1<a, b>, a, c>
type b = b1 & b2 & b3
// bluebird :: (b -> c) -> (a -> b) -> a -> c
const compose: b = curry((f, g, a) => f(g(a)))
//====[filter]=================================
type fil2 = <a>(p: p<a>, xs: a[]) => a[]
type fil1 = <a>(p: p<a>) => f1<a[], a[]>
type fil = fil1 & fil2
// filter :: (a -> Boolean) -> [a] -> [a]
const filter: fil = curry((p, xs) => {
const len = xs.length
const r = Array()
for (let [i, j] = [0, 0]; i < len; i++) {
const v = xs[i]
if (p(v)) {
r[j++] = v
}
}
return r
})
//====[mapArr]=================================
type m2 = <a, b>(f1: f1<a, b>, xs: a[]) => b[]
type m1 = <a, b>(f: f1<a, b>) => f1<a[], b[]>
type m = m2 & m1
// map :: (a -> b) -> [a] -> [b]
const mapArr: m = curry((fn, xs) => {
const len = xs.length
const r = Array(len)
for (let i = 0; i < len; i++) {
r[i] = fn(xs[i])
}
return r
})
//====[prop]===================================
type z2 = <o, k extends keyof o>(propName: k, source: o) => o[k]
type z1 = <o, k extends keyof o>(propName: k) => f1<o, o[k]>
type z = z2 & z1
// prop :: String -> a -> b
// prop :: Number -> a -> b
// prop :: Symbol -> a -> b
const prop: z = curry((propName, obj) => obj[propName])
data[]
;但是,如果我将鼠标悬停在
mappArr
函数上,TS将显示输入为
unknown[]
,因此会为
id
字段抛出错误的肯定。我究竟做错了什么?
//====[typescript test]===================================
interface data {
relationId: string
id: string
}
type isMine = p<data>
// isMine :: a -> Boolean
const isMine: isMine = x => x.relationId === '1'
type t = f1<data[], string[]>
const testFn: t = compose(
// @ts-ignore
mapArr(prop('id')),
//=> ^^^^^
// error TS2345: Argument of type '"id"' is not assignable to
// parameter of type 'never'.
filter(isMine)
)
//====[javascript test]================================
const r = testFn([
{ id: '3', relationId: '1' },
{ id: '5', relationId: '3' },
{ id: '8', relationId: '1' },
])
test('javascript is correct', () => {
expect(r).toEqual(['3', '8'])
})
const testFn: t = compose (mapArr(prop('id')))
(filter(isMine))
//=> ^^^^^^^^^^^^^^^
// error TS2322: Type 'unknown[]' is not assignable to type 'f1<data[], string[]>'.
// Type 'unknown[]' provides no match for the signature '(a: data[]): string[]'.
curry
的标准实现:
function isFunction (fn) {
return typeof fn === 'function'
}
const CURRY_SYMB = '@@curried'
function applyCurry (fn, arg) {
if (!isFunction(fn)) {
return fn
}
return fn.length > 1
? fn.bind(null, arg)
: fn.call(null, arg)
}
export function curry (fn) {
if (fn[CURRY_SYMB]) {
return fn
}
function curried (...xs) {
const args = xs.length
? xs
: [undefined]
if (args.length < fn.length) {
return curry(Function.bind.apply(fn, [null].concat(args)))
}
const val =
args.length === fn.length
? fn.apply(null, args)
: args.reduce(applyCurry, fn)
if (isFunction(val)) {
return curry(val)
}
return val
}
Object.defineProperty(curried, CURRY_SYMB, {
enumerable: false,
writable: false,
value: true,
})
return curried
}
最佳答案
无论我希望有多少,TypeScript都不是Haskell(或在此处插入您喜欢的类型化语言)。它的类型系统有很多漏洞,并且不能保证其类型推断算法会产生声音结果。它是not meant to be provably correct(启用惯用JavaScript更为重要)。公平地说,Haskell没有子类型,面对子类型的类型推断是more difficult。无论如何,这里的简短答案是:
不要试图依赖上下文类型(从函数输出中推断类型)
尝试依靠前向类型推断(从函数输入中推断类型)
当类型推断失败时,注释并指定类型。
由于TypeScript不是Haskell,所以我要做的第一件事就是使用TypeScript命名约定。另外,由于compose()
和其余的实现都不是问题,因此我将仅declare
这些功能并省略实现。
让我们来看看:
type Predicate<A> = (a: A) => boolean;
//====[compose]===============================
declare function compose<B, C>(
f: (x: B) => C
): (<A>(g: (a: A) => B) => (a: A) => C) & (<A>(g: (a: A) => B, a: A) => C); //altered
declare function compose<A, B, C>(f: (b: B) => C, g: (a: A) => B): (a: A) => C;
declare function compose<A, B, C>(f: (b: B) => C, g: (a: A) => B, a: A): C;
//====[filter]=================================
declare function filter<A>(p: Predicate<A>, xs: A[]): A[];
declare function filter<A>(p: Predicate<A>): (xs: A[]) => A[];
//====[mapArr]=================================
declare function mapArr<A, B>(f1: (a: A) => B): (xs: A[]) => B[];
declare function mapArr<A, B>(f1: (a: A) => B, xs: A[]): B[];
//====[prop]===================================
declare function prop<K extends keyof any>(
propName: K
): <O extends Record<K, any>>(source: O) => O[K]; // altered
declare function prop<K extends keyof O, O>(propName: K, source: O): O[K];
compose()
的第一个重载签名已从更改为
declare function compose<A, B, C>(
f: (x: B) => C
): ((g: (a: A) => B) => (a: A) => C) & ((g: (a: A) => B, a: A) => C);
declare function compose<B, C>(
f: (x: B) => C
): (<A>(g: (a: A) => B) => (a: A) => C) & (<A>(g: (a: A) => B, a: A) => C);
compose()
在
A
,
B
和
C
中是通用的,而是仅在
B
和
C
中是通用的,并返回在
A
中的通用函数。之所以这样做,是因为在TypeScript中,通常根据传递给函数的参数的类型(而不是函数的预期返回类型)进行泛型函数类型参数的推断。是的,有
contextual typing可以从所需的输出类型推断输入类型,但是它不如普通的“时间前向”推断可靠。
A
中调用一个泛型函数时,如果没有任何参数充当
A
的推理站点,可能会发生什么? (例如,当它只有一个类型为
(x: B) => C
的参数时)编译器将为
unknown
推断
A
(
as of TS3.5),以后您会不满意。通过将通用参数规范推迟到调用返回的函数之前,我们有更好的机会推断
A
您的意图。
prop()
的第一个重载从
declare function prop<K extends keyof O, O>(
propName: K,
): (source: O) => O[K];
declare function prop<K extends keyof any>(
propName: K
): <O extends Record<K, any>>(source: O) => O[K];
prop("id")
的调用将导致将
K
推断为
"id"
,并且可能将
O
推断为
unknown
,然后由于
"id"
不是已知是
keyof unknown
(即
never
)的一部分,您将收到错误消息。这很可能是引起您所看到的错误的原因。
O
的规范推迟到调用返回函数时使用。这意味着我需要将通用约束从
K extends keyof O
转换为
O extends Record<K, any>
...说类似的话,但方向相反。
compose()
测试会怎样?
//====[typescript test]===================================
interface Data {
relationId: string;
id: string;
}
type isMine = Predicate<Data>;
const isMine: isMine = x => x.relationId === "1";
const testFnWithFaultyContextualTyping: (a: Data[]) => string[] = compose(
mapArr(prop("id")), // error!
filter(isMine)
);
// Argument of type '<O extends Record<"id", any>>(source: O) => O["id"]'
// is not assignable to parameter of type '(a: unknown) => any'.
(a: Data[]) => string[]
,它触发了一些上下文类型,这些类型在正确推断
prop("id")
之前逐渐消失。在这种情况下,我的本能是尝试不依赖于上下文类型,而是查看常规类型推断是否起作用:
const testFn = compose(
mapArr(prop("id")),
filter(isMine)
); // okay
// const testFn: (a: Data[]) => string[]
testFn
是您期望的类型。
const testFnCurriedWithFaultyContextualTyping = compose(mapArr(prop("id")))( // error!
filter(isMine)
);
// Argument of type '<O extends Record<"id", any>>(xs: O[]) => O["id"][]'
// is not assignable to parameter of type '(x: unknown) => any[]'.
compose()
参数的类型。在这种情况下,无法通过移动通用类型来修复它。推断就不可能在这里发生。相反,我们可以依靠在
compose()
函数调用中显式指定泛型类型参数:
const testFnCurried = compose<Data[], string[]>(mapArr(prop("id")))(
filter(isMine)
); // okay
关于typescript - Typescript能够执行简单的功能组合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447070/
我已经写了并且 npm 发布了这个:https://github.com/justin-calleja/pkg-dependents 现在我正在用 Typescript 编写这个包:https://g
我有一个函数,我想在 TypeScript 中模拟它以进行测试。在我的测试中,我只关心 json和 status .但是,当使用 Jest 的 jest.spyOn 时我的模拟函数的类型设置为返回 h
我正在使用一个库 (Axios),它的包中包含 Typescript 声明。 我想声明一个将 AxiosResponse(在库的 .d.ts 文件中声明)作为参数的函数。我有以下内容: functio
我是 Typescript 的新手。我想使用 将一个 Typescript 文件加载到另一个 Typescript 文件中标签。 我做了一些事情,但它不起作用!请帮助我。 first.ts: imp
为什么我会收到下面屏幕截图中显示的错误? Atom 说我的 tsconfig.json“项目文件包含无效选项”用于 allowJs、buildOnSave 和 compileOnSave。 但是应该允
所以我正在创建一个 TypeScript 库,我可以轻松地将所有生成的 JS 文件编译成一个文件。有没有办法将所有 .ts 和 .d.ts 编译成一个 .ts 文件? 除了支持 JS 的版本(较少的智
Microsoft Research 提供了一种名为Safer TypeScript 的新 TypeScript 编译器变体: http://research.microsoft.com/en-us/
我需要这个来在单个文件中分发 TypeScript 中的库。有没有办法将多个 typescript 文件合并到(一个js文件+一个 typescript 定义)文件中? 最佳答案 要创建一个库,您可以
用例:我想知道一个函数在 typescript 中执行需要多少时间。我想为此目的使用装饰器。我希望装饰器应该返回时间以便(我可以进一步使用它),而不仅仅是打印它。 例如: export functio
我想检查一个类型是否可以为 null,以及它是否具有值的条件类型。 我尝试实现 type IsNullable = T extends null ? true : false; 但是好像不行 type
我的问题是基于这个 question and answer 假设我们有下一个代码: const myFn = (p: { a: (n: number) => T, b: (o: T) => v
我知道双重否定前缀,我知道 TypeScript 的单后缀(非空断言)。 但是这个双后缀感叹号是什么? /.*验证码为(\d{6}).*/.exec(email.body!!)!![1] 取自here
我正在使用以下文件结构在 Webstorm 中开发一个项目 | src | ... | many files | types | SomeInterface |
在 TypeScript 类中,可以为属性声明类型,例如: class className { property: string; }; 如何在对象字面量中声明属性的类型? 我试过下面的代码,但它
我正在寻找一种在不丢失推断类型信息的情况下将 TypeScript 中的文字值限制为特定类型的好方法。 让我们考虑一个类型Named,它保证有一个名字。 type Named = { name:
在 TypeScript 中,我想创建一个联合类型来表示属于一个或多个不同类型的值,类似于 oneOf在 OpenAPI或 JSON Schema .根据a previous answer on a
type Func = (foo:string) => void // function expression const myFunctionExpression:Func = function(f
假设我有一个联合类型,我正在使用类似 reducer 的 API 调用模式,看起来像这样: type Action = { request: { action: "create
我在 typescript 中有以下去抖功能: export function debounce( callback: (...args: any[]) => void, wait: numb
在 Vue3 的 defineComponent 函数中,第一个泛型参数是 Props,所以我在这里使用 Typescript 接口(interface)提供我的 props 类型。喜欢: expor
我是一名优秀的程序员,十分优秀!