type p = 't' | 'h'
function test(p: 't'): number
function test(p: 'h'): string
function test(p: 't' | 'h'): number | string {
if (p == "t") {
return 3
} else {
return ""
}
}
// 这个函数的类型是符合题目要求的但内部实现会报错,我不知道该怎么在不使用 any 和 @ts-ignore 的情况下实现
function test2(p:T): T extends 't' ? number : string {
if (p == "t") {
return 3
// Type 'number' is not assignable to type 'T extends "t" ? number : string'.
} else {
//@ts-ignore
return ""
}
}
interface Values {
a: string
b: number
[key: string]: unknown
}
type P = keyof Values
type T = Values['a']
type S = Values['b']
function isKeys(key: unknown): key is P {
return key === 'a' || key === 'b'
}
function getValue(key: Key): Values[Key]
function getValue(key: string): unknown {
const store: Values = {
a: "Hello",
b: 123,
}
if (isKeys(key)) {
return store[key]
}
return store[key]
}
// c is string
const c = getValue('a')
// d is number
const d = getValue('b')
// others is unknown
const e = getValue("fuck the world")