以下打字稿定义之间是否有区别:
function prop<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
和
function prop2<T>(obj: T, key: keyof T) {
return obj[key];
}
我的意思是不,但是也许我监督了一些事情。使用第一个版本(文档中经常使用的版本)有什么好处
答案 0 :(得分:8)
区别在于,在第一种情况下,返回类型为T[keyof T]
,在第二种情况下,返回类型为K
。 keyof T
最广泛的范围是K
,但它可以是表示键的特定字符串文字类型。这意味着,如果function prop<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
function prop2<T>(obj: T, key: keyof T) {
return obj[key];
}
let o = {
p1: 0,
p2: ''
}
let v = prop(o, 'p1') // is number, K is of type 'p1'
let v2 = prop2(o, 'p1') // is number | string, no extra info is captured
是特定属性,则返回值将与该属性具有相同的类型:
CREATE TABLE PERSON
(person_id int(10) not null AUTO_INCREMENT,
first_name varchar(15) not null,
last_name varchar(15) not null,
employee char(1),
participant char(1),
CONSTRAINT person_pk PRIMARY KEY (person_id))
ENGINE=InnoDB;
CREATE TABLE EMPLOYEE
(eperson_id int(10) not null AUTO_INCREMENT,
enterprise_email varchar(30),
manager_id int(10),
CONSTRAINT employee_pk PRIMARY KEY (eperson_id),
CONSTRAINT employee_fk1 FOREIGN KEY(eperson_id) REFERENCES PERSON(person_id) ON update cascade,
CONSTRAINT employee_fk2 FOREIGN KEY(manager_id) REFERENCES EMPLOYEE(eperson_id) ON update cascade)
ENGINE=InnoDB;
CREATE TABLE PARTICIPANT
(pperson_id int(10) not null AUTO_INCREMENT,
city varchar(30),
state varchar(2),
zip int(5),
sign_up_date date,
termination_date date,
CONSTRAINT participant_pk PRIMARY KEY (pperson_id),
CONSTRAINT participant_fk FOREIGN KEY(pperson_id) REFERENCES PERSON(person_id) ON update cascade)
ENGINE=InnoDB;