TypeScript如何使泛型成为必需?

huangapple go评论70阅读模式
英文:

How does typescript make generics mandatory?

问题

`export const test = <T>(a: string, { c, d }: { c: T[], d: T } = {}) => {}`

TypeScript如何使泛型强制性

我想定义一个具有T类型的函数,以便开发人员在使用时必须传入类型

test<string>()  正确
test<number>()  正确
test()   错误
英文:
`export const test = &lt;T&gt;(a:string,{c,d} = {c: T[], D:T} = {})=&gt;{} `

How does typescript make generics mandatory

I want to define a function that has a T type so that the developer must pass in the type when using it

test&lt;string&gt;()  ok
test&lt;number&gt;()  ok 
test()   error 

答案1

得分: 2

To disable type inference, disable type inference:

import { F } from 'ts-toolbelt'
function test<T = never>(a: string, b: F.NoInfer<T>[], c: F.NoInfer<T>) { }
//                ^ must have default, otherwise defaults to `unknown`

test('', [], '')
// function test<never>(a: string, b: never[], c: never): void

test<string>('', [''], '')
// ok

如果要禁用类型推断,请禁用类型推断:

https://millsp.github.io/ts-toolbelt/modules/function_noinfer.html
type NoInfer<A>: [A][A extends any ? 0 : never]

如果要防止使用简单参数,请使用以下代码:

type NoInfer<T> = [T][T extends any ? 0 : never];
type NeverIfNever<T> = [T] extends [never] ? never : any;

export const test = <T = never>(
    a: string & NeverIfNever<T>,
    { c, d }: { c?: NoInfer<T>[]; d?: NoInfer<T> } = {}
) => {};

test('', {})
// Argument of type 'string' is not assignable to parameter of type 'never'.(2345)

如果您有一个更复杂的单个函数参数,如果需要,请询问。

英文:

To disable type inference, disable type inference

import { F } from &#39;ts-toolbelt&#39;
function test&lt;T = never&gt;(a: string, b: F.NoInfer&lt;T&gt;[], c: F.NoInfer&lt;T&gt;) { }
//                ^ must have default, otherwise defaults to `unknown`

test(&#39;&#39;, [], &#39;&#39;)
// function test&lt;never&gt;(a: string, b: never[], c: never): void

test&lt;string&gt;(&#39;&#39;, [&#39;&#39;], &#39;&#39;)
// ok

https://millsp.github.io/ts-toolbelt/modules/function_noinfer.html
type NoInfer&lt;A&gt;: [A][A extends any ? 0 : never]


If you want to prevent usage of simple arg, use

type NoInfer&lt;T&gt; = [T][T extends any ? 0 : never];
type NeverIfNever&lt;T&gt; = [T] extends [never] ? never : any;

export const test = &lt;T = never&gt;(
    a: string &amp; NeverIfNever&lt;T&gt;,
    { c, d }: { c?: NoInfer&lt;T&gt;[]; d?: NoInfer&lt;T&gt; } = {}
) =&gt; {};

test(&#39;&#39;, {})
// Argument of type &#39;string&#39; is not assignable to parameter of type &#39;never&#39;.(2345)

If you have a single fn arg that's more hard, ask if needed

huangapple
  • 本文由 发表于 2023年4月13日 21:19:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定