打字稿,我很好奇它是否可以实现这种动态类型检查



这似乎有点不寻常。

interface APIS {
user: {
name: string;
age: number;
},
job: {
address: string;
company: string;
}
}
type Keys = keyof APIS;
/**
* params: key in Keys + '/' + k in keyof APIS[key]
*/
function getSomething(params: string) {
//
}
getSomething('user/name');     // yes
getSomething('user/age');      // yes
getSomething('job/address');   // yes
getSomething('job/company');   // yes

getSomething('job/name');      // no
getSomething('user/address');  // no

params 是一个串联的字符串,Typescript 可以做类型检查吗? 谁能提供想法也可以?

通常可以使用path函数执行此操作:

interface APIS {
user: {
name: string;
age: number;
},
job: {
address: string;
company: string;
}
}
const x: APIS = {
user: {
name: "n",
age: 1,
},
job: {
address: "add",
company: "c"
}
}
const path2 = <T, K1 extends keyof T>(k1: K1, k2: keyof T[K1], o: T) => o[k1][k2];
console.log(path2('user', 'name', x))

但我相信你必须为每个路径的"深度"编写单独的函数,因为你需要能够为每个路径指定一个泛型。我猜可能有一种方法可以解决这个问题(但我现在想不起来(。

我建议你最好想办法进一步分解你想做的事情:

const path = <T>(p: keyof T) => (x: T) => x[p];
const compose2 = <T, U, V>(
f: (x: U) => V,
g: (x: T) => U,
) => (x: T) => f(g(x));

interface APIS {
user: {
name: string;
age: number;
},
job: {
address: string;
company: string;
}
}
const x: APIS = {
user: {
name: "n",
age: 1,
},
job: {
address: "add",
company: "c"
}
};
const getName = compose2(path('name'), path('user'));
const getCompany = compose2(path('company'), path('job'));
const testA = getName(x);
const testB = getCompany(x);
console.log(testA);
console.log(testB);

然而,就你实际想做的事情而言;你说的是Typescript能够解析串联的字符串文字类型;这似乎是不可能的(见这个问题(。有很多兴趣,但似乎还没有太多的解决方案。

最新更新