是否可以设置默认的泛型类型?

时间:2017-04-27 16:11:15

标签: typescript

是否可以根据另一个参数动态限制参数类型?

type Foo = {
    bar: string;
    baz: number;
}

let o: Foo;

function setProperty(key: keyof Foo, value: Foo[keyof Foo]) {
    o[key] = value;
}

setProperty("bar", 55); // shouldn't be allowed
setProperty("bar", "55"); // allowed

1 个答案:

答案 0 :(得分:2)

lookup types与泛型一起使用:

type Foo = {
    bar: string;
    baz: number;
}

let o: Foo;    

function setProperty<P extends keyof Foo> (key: P, value: Foo[P]) {
    o[key] = value;
}

setProperty("bar", 55); // Throws error
setProperty("bar", "55"); // allowed