请教TS的泛型条件约束问题?
演示代码:https://tsplay.dev/N5jo0m
interface Base {
name: string;
age: number;
};
interface FixedInstance extends Base {}
interface FollowInstance extends Base {}
type NameType = "fixed"|"follow";
type FixedName = "fixed";
type FollowName = "follow";
const data: NameType = 'fixed';
type myType = typeof data;
type isFixed = myType extends FixedName ? true : false; // true
type isFollow = myType extends FollowName ? true : false; // false
// -----------cut---
function sellect<T extends NameType, U = T extends FixedName ? FixedInstance : FollowInstance>(name: T, data: U) {
return {
name, data
};
}
const { name: myName, data: myData } = sellect("fixed", { name: "levi", age: 18 } as FollowInstance);
type dataType = typeof myData;
type dataisFixed = myType extends FixedName ? true : false; // true
type dataisFollow = myType extends FollowName ? true : false; // false
从cut
以上,可以看到都是正确的,问题在函数sellect
- 我需要根据第一个参数
name: T
去判断第二个参数data
的类型 - 提供的
name
是fixed
就限制data
是FixedInstance
,否则就限制为FollowInstance
问题1:我在sellect
参数传参的时候故意 as FollowInstance
,在TS中并没有报错问题2:在拿到的结果中dataisFixed
是true
,但是我传过去的是FollowInstance
回复
1个回答

test
2024-06-23
修改如下
interface Base {
name: string;
age: number;
};
interface FixedInstance extends Base {}
interface FollowInstance extends FixedInstance {
sex: 1|2;
}
type NameType = "fixed"|"follow";
type FixedName = "fixed";
type FollowName = "follow";
const data: NameType = 'fixed';
type myType = typeof data;
type isFixed = myType extends FixedName ? true : false; // true
type isFollow = myType extends FollowName ? true : false; // false
// -----------cut---
function sellect<T extends NameType>(name: T, data: T extends FixedName ? FixedInstance : FollowInstance) {
return {
name, data
} as const;
}
const infodata: FixedInstance = { name: "levi", age: 18 };
const { name: myName, data: myData } = sellect("follow", infodata);
type dataType = typeof myData;
type dataisFixed = myType extends FixedName ? true : false; // false
type dataisFollow = myType extends FollowName ? true : false; // false
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容