Skip to content

使用泛型和 keyof 约束参数

Published:

示例代码

function onUpdateStuff
	<T extends Object,
   K extends keyof T
   // value: T[K]
  >
	(object: T,  props: K): void
{
	....
  // obj[key] = value
}

const gender = {
    male: 1,
    female: 2,
    private: 3
}

const status = {
    disabled: 0,
    enabled: 1
}

// Argument of type '""' is not assignable to parameter of type '"male" | "female" | "private"'.(2345)
onUpdateStuff(gender, '')