Typescript equivalent of ? unknown wildcard

后端 未结 2 1696
悲哀的现实
悲哀的现实 2020-12-20 12:09

Say I want to declare an array of generics in Typescript. What would be the equivalent of the unknown wildcard \'?\' in Java?

This does compile, but seems a little a

相关标签:
2条回答
  • 2020-12-20 12:54

    I don't think Typescript has late binding generic types.

    But if this particular code was in the context of a function you could use generics to achieve a similar thing.

    function example<T>(val:T){
      let a : T[]
    
      return [val]
    }
    
    let a = example(4)
    // number[] :: [4]
    
    let b = example('hello')
    // string[] :: ['hello']
    

    Here is an interactive example: link

    Try hovering over a or b to see it in action.

    0 讨论(0)
  • 2020-12-20 12:54

    Say I want to declare an array of generics in Typescript. What would be the equivalent of the unknown wildcard '?' in Java?

    To have a string array

    var foo:string[]; 
    

    This is same as the following as far as TypeScript is concerned:

    var foo:Array<string>; 
    

    If you want an array of anything then just use any:

    var foo:any[] = ['asdf',123]; // Anything is allowed in this array.
    
    0 讨论(0)
提交回复
热议问题