When is it possible to omit “generic types” in TypeScript?

I noticed that, often, the TypeScript compiler doesn’t complain if I don’t pass a parametrised type:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function someFunction<T>(): T {
// Do something
}
const x = someFunction<string>();
// I'd personally expect this line to ALWAYS raise a compiler error
// but this is not the case
const y = someFunction();
</code>
<code>function someFunction<T>(): T { // Do something } const x = someFunction<string>(); // I'd personally expect this line to ALWAYS raise a compiler error // but this is not the case const y = someFunction(); </code>
function someFunction<T>(): T {
  // Do something
}

const x = someFunction<string>();

// I'd personally expect this line to ALWAYS raise a compiler error
// but this is not the case
const y = someFunction();

In some cases it does raise an error, other times it doesn’t, and I don’t see a pattern behind this behaviour.

I guess that, in some cases, the structure of the function itself suggests the compiler what the type T is, and in those cases it’s probably correct that it doesn’t get flagged.

But I did a couple of experiments, and there are confusing results.

  1. Experiment 1

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function cannotBeInferred<T>(): T {
    return 0 as T;
    }
    const a1 = cannotBeInferred();
    const a2 = cannotBeInferred<string>();
    </code>
    <code>function cannotBeInferred<T>(): T { return 0 as T; } const a1 = cannotBeInferred(); const a2 = cannotBeInferred<string>(); </code>
    function cannotBeInferred<T>(): T {
      return 0 as T;
    }
    
    const a1 = cannotBeInferred();
    const a2 = cannotBeInferred<string>();
    
    • Variable a1 is unknown: I’d definitely expect the compiler to raise an error
    • Variable a2 is string, as expected
  2. Experiment 2

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function canBeInferredNativeType<T>(par: T): T {
    return par;
    }
    const b1 = canBeInferredNativeType('test');
    const b2 = canBeInferredNativeType<string>('test');
    </code>
    <code>function canBeInferredNativeType<T>(par: T): T { return par; } const b1 = canBeInferredNativeType('test'); const b2 = canBeInferredNativeType<string>('test'); </code>
    function canBeInferredNativeType<T>(par: T): T {
      return par;
    }
    
    const b1 = canBeInferredNativeType('test');
    const b2 = canBeInferredNativeType<string>('test');
    
    • Variable b1 is of type "test" – I’d expect the compiler to raise an error here
    • Variable b2 is string as expected
  3. Experiment 3

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function canBeInferredInterface<T>(param: { something: T }): T {
    return param.something;
    }
    interface Something { something: string };
    const param: Something = { something: 'blabla' };
    const c1 = canBeInferredInterface({ something: 'test' });
    const c2 = canBeInferredInterface(param);
    const c3 = canBeInferredInterface<number>({ something: 123 });
    </code>
    <code>function canBeInferredInterface<T>(param: { something: T }): T { return param.something; } interface Something { something: string }; const param: Something = { something: 'blabla' }; const c1 = canBeInferredInterface({ something: 'test' }); const c2 = canBeInferredInterface(param); const c3 = canBeInferredInterface<number>({ something: 123 }); </code>
    function canBeInferredInterface<T>(param: { something: T }): T {
      return param.something;
    }
    
    interface Something { something: string };
    const param: Something = { something: 'blabla' };
    
    const c1 = canBeInferredInterface({ something: 'test' });
    const c2 = canBeInferredInterface(param);
    const c3 = canBeInferredInterface<number>({ something: 123 });
    
    • Variable c1 is string; I’d expect the compiler to raise an error here, because how does it know that the interface I am passing is { something: string } and not { something: 'test' }?
    • Variable c2 is string; in my view it’s correct that the compiler didn’t raise an error, because the parameter I am passing is explicitly typed; but I do find this example a bit convoluted, I’d still prefer the compiler to fail here
    • Variable c3 is correctly number

What I would like is a uniform behaviour. Either raise an error every single time that I don’t provide the parameter; or otherwise be crystal clear that, when errors are not raised, it means that the type is obvious from the context.

How can I achieve this? Is there a compiler option for this?

2

It is possible to omit generic type parameters in Typescript as soon as:

  • They’re optional, ie when a defautl value has been specified
    type Type<Optional = string> = .....
    => you can use Type without specifying the generic parameter but then it will be string
  • They are inferable and not partially specified
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>type Func<Input, Return> = (input: Input) => Return;
const hoist = <Input, Return>(func: Func<Input, Return>, input: Input) => {
return func(input);
}
const hoistReturnNumber = <Input, Return = number>(func: Func<Input, Return>, input: Input) => {
return hoist<Input, Return>(func, input);
}
// none specified, fully inferable => OK
hoist((a: string) => parseInt(a), '12')
// first specified, second optional => OK
hoistReturnNumber<string>((a: string) => parseInt(a), '12')
// fully inferable but first specified while second mandatory => ERROR
hoist<string>((a: string) => parseInt(a), '12')
// fully specified
hoist<string, number>((a: string) => parseInt(a), '12')
</code>
<code>type Func<Input, Return> = (input: Input) => Return; const hoist = <Input, Return>(func: Func<Input, Return>, input: Input) => { return func(input); } const hoistReturnNumber = <Input, Return = number>(func: Func<Input, Return>, input: Input) => { return hoist<Input, Return>(func, input); } // none specified, fully inferable => OK hoist((a: string) => parseInt(a), '12') // first specified, second optional => OK hoistReturnNumber<string>((a: string) => parseInt(a), '12') // fully inferable but first specified while second mandatory => ERROR hoist<string>((a: string) => parseInt(a), '12') // fully specified hoist<string, number>((a: string) => parseInt(a), '12') </code>
type Func<Input, Return> = (input: Input) => Return;

const hoist = <Input, Return>(func: Func<Input, Return>, input: Input) => {

 return func(input);
}

const hoistReturnNumber = <Input, Return = number>(func: Func<Input, Return>, input: Input) => {

 return hoist<Input, Return>(func, input);
}

// none specified, fully inferable => OK
hoist((a: string) => parseInt(a), '12')

// first specified, second optional => OK
hoistReturnNumber<string>((a: string) => parseInt(a), '12')

// fully inferable but first specified while second mandatory => ERROR
hoist<string>((a: string) => parseInt(a), '12')

// fully specified
hoist<string, number>((a: string) => parseInt(a), '12')

Now even if it triggers OCD, having infered generic parameters allows for deep inference and really generic code that will not need painfull refactoring when the manipulated types change.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật