Skip to content

TypeScript : keyof T

ythy edited this page Aug 24, 2017 · 4 revisions

generic用法

以Combobox数据源为例, 数据源类型为Array<T>, labelFiled属性可设置为 keyof T, 例子:

class Select<T>{   
  mLabelFiled:keyof T = null;
  mSelectIndex:number = -1;
  mData:Array<T>;   

  constructor(public $container:JQuery){
  }   

  set dataProvider(data:Array<T>){
    this.mData = data;
  }

  set selectedIndex(index:number){
    let text:T[keyof T] = '';
    text = this.mData[index][this.mLabelFiled];
    $('#select_showtext').html(text);
  }   
}  

generic 实例化问题

实例化Class 要标明T类型, 例子:

class RadioGroup<T>{  
  setup(elem:JQuery, data:Array<T>, keyName: keyof T):RadioGroup<T>{  
    return this;  
  }  
}  

mSpecRadioGroup:URadioGroup<MItemSpecInfo>;  
this.mSpecRadioGroup = new URadioGroup<MItemSpecInfo>().setup($('#specbox'),   
                       this.mCurrentSpecData.itemSpecInfo, 'specName' )

以上 如果 new URadioGroup<MItemSpecInfo>() 不标明T类型的话 keyName: keyof T 此参数类型会变为 never

Clone this wiki locally