英文:
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 = <T>(a:string,{c,d} = {c: T[], D:T} = {})=>{} `
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<string>() ok
test<number>() 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 '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]
If you want to prevent usage of simple arg, use
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)
If you have a single fn arg that's more hard, ask if needed
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论