English 中文(简体)
如何避免牵引空阵列
原标题:How to avoid inferring empty array

我有以下文字编码:

function loader<P extends [], T>(load: (...args: P) => Promise<T>, lazy = false) {
    const result: { value?: T, error?: unknown } = {}
    function start(...args: P) {
        load(...args)
            .then(v => result.value = v)
            .catch(e => result.error = e)
    }

    // Argument of type  []  is not assignable to parameter of type  P .
    if (!lazy) start()

    return { restart: start, result }
}

const load = (a = 1, b = 2) => Promise.resolve(a + b)

// restart is () => void
const { restart, result } = loader(load)

我需要限制参数<代码><<>载荷/代码>,以便能够在没有参数的情况下使用,即没有参数,或者所有参数都是选择性的。 功能<代码>start。

此外,我希望restartload有相同的参数清单。 页: 1 应为(a?: number, b?: number) => Promise< number>

问题回答

考虑以下守则:

const a = [1, 2, 3];
const b: [] = a;

你可以看到以下错误信息:

Type  number[]  is not assignable to type  [] .
  Target allows only 0 element(s) but source may have more.

实际上,<代码>[a?: number hexachloro> Defin, b?: number > un Defin] not lif []/code>。

Instead of <P extends [], T>, use <P extends any[], T> to solve this issue.

TS Playground





相关问题
Generic constraint exclusion

Sorry for asking silly question Is it possible to enforce constraint on generic in such a way that the given T can be derived from any reference Type except some A,B,C (where A,B,C are reference ...

Can a Type Derive from Itself?

When enforcing a Generic constraint class GenericTest { public void Sample<T>(T someValue) where T:Racer,new() { Console.WriteLine(someValue.Car); } } The Type T should be ...

C# Deriving Generic Methods

When i need to pass a Generic Type I can use the Syntax (Example : Ofcourse it is not a Generic Method) public void Sample(T someValue) { ...... } What is the benefit of declaring Sample<T>...

What is the benefit to using List<T> over IEnumerable<T>?

or the other way around? I use generic lists all the time. But I hear occasionally about IEnumerables, too, and I honestly have no clue (today) what they are for and why I should use them. So, at ...