Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ts的一些题目 #22

Open
keep-run opened this issue Apr 15, 2020 · 0 comments
Open

ts的一些题目 #22

keep-run opened this issue Apr 15, 2020 · 0 comments

Comments

@keep-run
Copy link
Owner

  1. 写一个函数,接受两个参数,一个为object,另一个为object中的一个key。函数返回类型指定为obj[key]的类型。
interface Person{
	name:string,
	age:number
}

// 函数不显示设置返回值的类型,利用动态推导得出
function demo<T extends object, K entends keyof T>(obj:T, key:K){
	return obj[k]
}

//测试
let obj:Person={
 	 name:"tea",
 	 age:23
}
let age = demo(obj, "age")   // number类型
let name = demo(obj, "name")   // string类型
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant