如何用任意键声明一个类型化的对象?

时间:2016-04-13 06:27:35

标签: typescript

T文件中,如何将对象定义为具有字符串键和declare var Game: { creeps: Object<string, Creep>; // not sure what syntax to use here }; declare class Creep { // definition... } 值?

e.g。

Game.creeps

objectCreep,但我不知道它将具有哪些属性/键(它们是在运行时定义的 - 我使用它像字典一样),但是,我知道它的所有值都是SELECT SQL_CALC_FOUND_ROWS (FOUND_ROWS() ) as total, (SELECT GROUP_CONCAT(sp.specialization) FROM DSpecialization_Master dsp LEFT JOIN Specialization_Master sp on sp.id = dsp.specialization WHERE dsp.profileid = pm.id and (dsp.specialization = (select id from Specialization_master where specialization='Dentist' ))) as drspec , pm.id as profileid, pm.loginid as loginid, dam.clinicname, dam.area, dam.address, dam.pincode, dam.id as addressid, dam.feecharge as feecharge, pm.fname, pm.lname, pm.email, pm.mobile, pm.phone, pm.gender, pm.dob, pm.totexp, pm.imagepath, pm.languages, pm.statement, pm.createdby, um.profile_url, um.clinic_url, pm.hsbit, (SELECT GROUP_CONCAT(education) FROM DEducation_Master WHERE profileid = pm.id ) as dredu FROM Profile_Master pm LEFT JOIN DAddress_Master dam on dam.profileid = pm.id left join Unique_Url_Master um on um.clinicid =dam.id WHERE dam.city='Surat' and pm.id IN (SELECT profileid FROM DSpecialization_Master WHERE specialization = (select id from Specialization_master where specialization='Dentist')) ORDER BY pm.id limit 0 , 10 s。

我的IDE说“对象不是通用的”所以我猜这种语法不太正确。

2 个答案:

答案 0 :(得分:9)

使用索引签名

declare var Game: {
    creeps: {[key:string]: Creep}
};

答案 1 :(得分:1)

basrat的答案仍然可以正常工作,但是在Typescript 2.1或更高版本中,有一种打字看起来与您最初认为的可能更相似:

declare var Game: {
    creeps: Record<string, Creep>
};

没有什么真正的区别,尽管我补充说Typescript假设对于任何K值,Record<K, V>都可以产生相应的V值。例如:

type Creep = {
    id: number;
}

function printIt(c: Creep) {
    console.log(c.id);
}

let game: Record<string, Creep> = {"test": {id: 0}};
printIt(thing["quest"]);
尽管

肯定会导致运行时错误,但即使使用strictNullChecks也会编译。因此,您需要自己检查索引访问,和/或按照建议的@mpen使用--noUncheckedIndexedAccess标志。